When I compile the following code, compiler gives me the warning:
"Implicit conversion loses integer precision: 'std::streamsize' (aka 'long') to 'int'".
I’m a little bit confused about this warning since I just try to save the current value of the precision to set it back to the original value later.
#include <iomanip>
#include <iostream>
int main() {
std::streamsize prec = std::cout.precision();
std::cout << std::setprecision(prec);
}
What is the right way to save the precision value and set it back later in this case?
It looks like it’s just an oversight in the standard specification.
ios_base::precisionhas two overloads, one that gets and one that sets the precision:So this code will not give you warnings:
However, the
setprecision()function simply takes a plain oldint:and returns an unspecified functor, which when consumed by a stream
strhas the effect of:In your case,
streamsizeis not anint(and does not have to be), hence the warning. The standard should probably be changed so thatsetprecision‘s parameter is notint, butstreamsize.You can either just call
precison()yourself, as above, or assumeintis sufficient and cast.Edit: Apparently it was submitted to be fixed and reached no concensus (closed as not-a-defect).