Search code examples
c++inputfloating-pointfloating-point-conversion

Reading float with C++ input operator


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.


Solution

  • 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".