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?
std::setprecision
stream modifier was an exception. – Grainger>>
overload for all manips.... – Icosahedron