我有一堆整数,我把它们放进了 stringstream
中。现在我想将这些 stringstream
转换为 string
,同时保持字符串的常量精度。我该如何做?我知道可以使用 stringstreams.precision()
,但由于某种原因它不起作用:
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
3.0
而不是3.00
。 - noobcppfixed
或者scientific
模式。尝试进行更改并查看是否解决了问题。 - templatetypedefprecision
函数单独放在一行上:t << setprecision(2) << fixed << a ...
- user470379