C++ std::stringstream 的小数点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5113221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:25:12  来源:igfitidea点击:

Decimal points with std::stringstream?

c++stringfloating-pointstringstreamiomanip

提问by noobcpp

I have a bunch of integers that I put into stringstreams. Now I want to change the stringstreams into strings while keeping a constant precision with the strings. How would I do that? I know I can use stringstreams.precision(), but it's not working for some reason:

我有一堆整数放入stringstreams 中。现在我想将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";

Will return 5.23\n3.134\n3.0, rather than 5.23\n3.13\n3.00

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

回答by templatetypedef

I think that your problem is that precision()sets the precision used in future stream insertion operations, not when generating the final string to present. That is, by writing

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

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

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

You're setting precisiontoo late, as the first three lines have already converted the floating point numbers to strings using the default precision.

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

To fix this, try changing the order in which you execute these statements to

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

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

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

This will cause the writes into the stringstreamto use your custom precision rather than the existing defaults.

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

However, the effect of the precisionmodifier is only meaningful if you explicitly tell the stream that you want to use either fixed-precision or scientific notation for output. To do this, you can use either the fixedor scientificmodifiers:

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

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

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

This will correctly display the appropriate number of digits.

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

On a related note, you don't need to use three stringstreams to accomplish your goal. You can just use one:

与此相关的是,您不需要使用三个stringstreams 来实现您的目标。你可以只使用一个:

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

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

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