Reading float with C++ input operator

13,947

Solution 1

See the info for "(1) arithmetic types" in the std::istream::operator>> docs. This uses num_get::get() and the relevant part of the docs for that states "The function stops reading characters from the sequence as soon as one character cannot be part of a valid numerical expression".

So from the documentation it seems that all available digits will be read, but they won't all be used if the float type is too "narrow".

Solution 2

You can test parts of this with a little experiment:

#include <iostream>

int main(void) {
    float f;
    std::string s;

    std::cin >> f;
    std::cin >> s;

    std::cout << f << std::endl;
    std::cout << s << std::endl;

    return 0;
}

Then compile:

$ g++ --version
g++ (GCC) 4.8.2
...

$ g++ -std=c++11 -pedantic -Wextra -Wall ./fltest.cpp

And run with input that you know has more digits than a float has:

$ echo '3.1415926535 foo' | ./a.out
3.14159
foo

So it seems that the extraneous extra precision is discarded (a single-precision floating-point number has a litte more than 7 decimal digits of precision.

You can play with the input and output precision to see what effects these have by putting, say:

std::cin.precision(7);

before the std::cin >> f; line or, say:

std::cout.precision(10);

before the std::cout << f; line.

Share:
13,947
san
Author by

san

Updated on June 05, 2022

Comments

  • san
    san almost 2 years

    Consider

    float num;
    cin >> num;
    

    Is it well defined how many characters of the input this code can consume. I am particularly interested in the case where the input stream may have the num specified in a much higher precision than what the float type can represent. So, in this case is it standardized whether the code would read all of it (up to but not including the next non-numeric input), or just up to the max precision of float.

  • san
    san about 10 years
    Had tried out a similar test, but wanted to know if this was a well defined behavior I can rely on. It turns out that it is indeed defined. More than whether it discards extra precision (it has to, float just cant represent them) was concerned how much of the input does the operator consume. It consumes up to the first character that cannot be part of a float literal.