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

1

7

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?

Icosahedron answered 16/3, 2023 at 17:42 Comment(2)
Probably easier to let the code compile for this one case than to try and fix it such that the std::setprecision stream modifier was an exception.Grainger
@RichardCritten this was one of my first ideas, but only on a second thought I actually understand it ;). iomanips are just functions and there is only one >> overload for all manips....Icosahedron
S
4

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.

Symbology answered 16/3, 2023 at 18:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.