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
Decimal points with std::stringstream?
提问by noobcpp
I have a bunch of integers that I put into stringstream
s. Now I want to change the stringstream
s into string
s while keeping a constant precision with the string
s. How would I do that? I know I can use stringstreams.precision()
, but it's not working for some reason:
我有一堆整数放入stringstream
s 中。现在我想将stringstream
s更改为string
s,同时保持 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 precision
too 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 stringstream
to use your custom precision rather than the existing defaults.
这将导致写入stringstream
使用您的自定义精度而不是现有的默认值。
However, the effect of the precision
modifier 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 fixed
or scientific
modifiers:
但是,precision
只有当您明确告诉流您要使用固定精度或科学记数法进行输出时,修饰符的效果才有意义。为此,您可以使用fixed
或scientific
修饰符:
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 stringstream
s to accomplish your goal. You can just use one:
与此相关的是,您不需要使用三个stringstream
s 来实现您的目标。你可以只使用一个:
std::stringstream t;
t.precision(2);
t << fixed << a << '\n' << b << '\n << c << '\n';
std::string out = t.str();