std :: stringstream的小数点?

noo*_*cpp 26 c++ string floating-point stringstream iomanip

我有一堆整数,我把它放进去了stringstream.现在我想将stringstreams改为strings,同时保持s的恒定精度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";
Run Code Online (Sandbox Code Playgroud)

会回来5.23\n3.134\n3.0,而不是5.23\n3.13\n3.00

tem*_*def 46

我认为您的问题是precision()设置未来流插入操作中使用的精度,而不是在生成要呈现的最终字符串时.也就是说,通过写作

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

ta.precision(2);
tb.precision(2);
tc.precision(2);
Run Code Online (Sandbox Code Playgroud)

你设置precision太晚了,因为前三行已经使用默认精度将浮点数转换为字符串.

要解决此问题,请尝试更改执行这些语句的顺序

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

ta << a;
tb << b;
tc << c;
Run Code Online (Sandbox Code Playgroud)

这将导致写入stringstream使用您的自定义精度而不是现有默认值.

但是,precision修饰符的效果仅在您明确告诉流要使用固定精度或科学记数法输出时才有意义.为此,您可以使用fixedscientific修饰符:

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

ta << fixed << a;
tb << fixed << b;
tc << fixed << c;
Run Code Online (Sandbox Code Playgroud)

这将正确显示适当的位数.

在相关的说明中,您不需要使用三个stringstream来完成目标.你可以使用一个:

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

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

std::string out = t.str();
Run Code Online (Sandbox Code Playgroud)

  • 你不需要在一个单独的行上拆分`precision`调用:`t << setprecision(2)<< fixed << a ...` (13认同)
  • 2年后,这篇文章仍在拯救生命!谢谢@templatetypedef (5认同)
  • 谢谢,但它不起作用.我仍然得到"3.0"而不是"3.00" (2认同)

vit*_*aut 8

在 C++20 中,您可以使用std::format比以下命令更高效且更简洁的命令std::stringstream

float a = 5.23;
float b = 3.134;
float c = 3.0;
std::string out = std::format("{:.2f}\n{:.2f}\n{:.2f}\n", a, b, c);
Run Code Online (Sandbox Code Playgroud)

同时您可以使用基于( godbolt ) 的{fmt} 库std::format

免责声明:我是 {fmt} 和 C++20 的作者std::format