2015-01-15 34 views
1

我想將sprintf語句轉換爲C++流語句。 我試圖複製sprintf的格式聲明「%5.3f」C++流iomanip相當於sprintf「%5.3f」

我使用空間std,並已列入和

我:

double my_double = GetMyDoubleFromSomewhere(); 

stringstream ss; 

ss << ??? << my_double; 

我一直在尋找在固定和setprecision,但不能完全弄清楚如何設置原始格式說明符的5和3?

+2

'SS <<的std :: setwidth(5)<<的std :: setprecision(3)'? –

+0

@MarkShevchenko不,不是這樣的:你會爲'123.45678'而不是''123.567「'得到'123''。 – dasblinkenlight

+1

我個人很懶,使用[boost.format](http://www.boost.org/doc/libs/1_57_0/libs/format/index.html) – Mgetz

回答

5

setprecisionsetw會幫助你。 不要忘記包括iomanip

#include <iostream> 
#include <iomanip> 
#include <stdio.h> 

int main(void) { 
    using namespace std; 
    double target = 1.2345; 

    cout << fixed << setw(5) << setprecision(3) << target << endl;; 
    printf("%5.3f\n", target); 
} 
+1

這是一個有用的[demo](http://ideone.com/AM7KS3) –

1

您要使用的IO操縱std::setwstd::setprecision,是這樣的:

ss << std::setw(5) << std::setprecision(3) << my_double;