cppreference says:
When used in an expression
out << setprecision(n)
orin >> setprecision(n)
, sets the precision parameter of the streamout
orin
to exactlyn
.
The example on the bottom of the same page demonstrates the use with std::cout
.
Also for inputstreams the page explains that str >> setprecision(n)
is effectively the same as calling a funciton that calls str.precision(n)
. But what for? What is the effect of std::cin >> setprecision(n)
?
This code
#include <iostream>
#include <iomanip>
int main() {
double d;
std::cin >> std::setprecision(1) >> d;
std::cout << d << "\n";
std::cin >> std::fixed >> std::setprecision(2) >> d;
std::cout << d << "\n";
}
With this input:
3.12
5.1234
Produces this output:
3.12
5.1234
So it looks like it has no effect at all. And reading about std::ios_base::precision
it also seems like precision only makes sense for out streams:
Manages the precision (i.e. how many digits are generated) of floating point output performed by
std::num_put::do_put
.
What is the reason std::setprecision
can be passed to std::istream::operator>>
, when, according to cppreference, it effectively calls str.precision(n)
which only affects output?
Using setprecision
with either <<
on a std::basic_ostream
or >>
on a std::basic_istream
has the exact same effect, affecting only how output on the stream will be handled. The precision attribute is stored in the virtual std::ios_base
base class, which is unified among input and output streams, which is why it still can work on an input stream.
But on a pure input stream I don't see any application for it. On a bidirectional stream however, this allows using both <<
or >>
to set the output precision.
Whether there is a specific benefit to allowing setprecision
with >>
isn't clear to me. This originally wasn't in the first C++ standard draft, but was added with a CD ballot comment to C++98, see comment CD2-27-015 in N1064. Unfortunately the comment doesn't give a rationale.