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:
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
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 writingYou're setting
precision
too late, as the first three lines have already converted the floating point numbers to strings using the default precision.To fix this, try changing the order in which you execute these statements to
This will cause the writes into the
stringstream
to use your custom precision rather than the existing defaults.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 thefixed
orscientific
modifiers: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: