463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123440

Whats the use of std::cin >> setprecision(n)?

cppreference says:

When used in an expression out << setprecision(n) or in >> setprecision(n), sets the precision parameter of the stream out or in to exactly n.

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?

Upvotes: 7

Views: 509

Answers (1)

user17732522
user17732522

Reputation: 76889

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.

Upvotes: 4

Related Questions