2011-02-25 44 views
22

我有一堆整數,我把它放入stringstream s。現在我想將stringstream s更改爲string s,同時保持與string s的恆定精度。我會怎麼做?我知道我可以使用stringstreams.precision(),但它不工作的一些原因:小數點與std :: stringstream?

float a = 5.23; 
float b = 3.134; 
float c = 3.0; 

std::stringstream ta; 
std::stringstream tb; 
std::stringstream tc; 

ta << a; 
tb << b; 
tc << c; 

ta.precision(2); 
tb.precision(2); 
tc.precision(2); 

std::string out = ""; 
out += ta.str() + "\n"; 
out += tb.str() + "\n"; 
out += tc.str() + "\n"; 

將返回5.23\n3.134\n3.0,而不是5.23\n3.13\n3.00

回答

43

我認爲你的問題是,precision()將在未來的流插入操作中使用的精確度,而不是在生成最後一個字符串時出現。也就是說,通過寫

ta << a; 
tb << b; 
tc << c; 

ta.precision(2); 
tb.precision(2); 
tc.precision(2); 

你設置precision爲時已晚,爲第一三線已經轉換的浮點數使用默認精度字符串。

要解決這個問題,請嘗試更改您在其中執行這些語句來

ta.precision(2); 
tb.precision(2); 
tc.precision(2); 

ta << a; 
tb << b; 
tc << c; 

這將導致寫入stringstream能夠使用自定義精度而非現有默認順序。

但是,precision修飾符的效果僅在您明確告訴流要使用固定精度或科學記數法輸出時纔有意義。要做到這一點,您可以使用該fixedscientific修飾符:

ta.precision(2); 
tb.precision(2); 
tc.precision(2); 

ta << fixed << a; 
tb << fixed << b; 
tc << fixed << c; 

這將正確顯示的數字適當數量。

在相關說明中,您不需要使用三個stringstream即可完成您的目標。你可以用一個:

std::stringstream t; 
t.precision(2); 

t << fixed << a << '\n' << b << '\n << c << '\n'; 

std::string out = t.str(); 
+2

謝謝,但它不工作。即時通訊仍然獲得'3.0'而不是'3.00' – noobcpp

+0

@ noobcpp-哎呀!我的錯。我只是更新了這一點,提到你需要在字串流上使用'fixed'或'scientific'模式。嘗試做出改變,看看它是否修復了一些事情。 – templatetypedef

+0

+1。 @noobcpp:另外,看看:http://www.cplusplus.com/reference/iostream/ios_base/precision/(儘管他們說在一個給我編譯器錯誤的地方使用0)。 –

相關問題