lundi 5 octobre 2015

Value stored when istream read fails

Sample code:

#include <iostream>

int main()
{
    int x = 5;
    std::cin >> x;
    std::cout << x << '\n';
}

On one particular implementation the following behaviour occurs:

  • Input: 6; output 6
  • Input: a; output: 0
  • Input: (end-of-file); output 5
  • Input: (whitespace followed by end-of-file); output 5

So, on failure, the cin >> x is assigning 0 to x if it was a failure to convert text to int; but it is not assigning 0 if the failure was due to end-of-file.

Is this correct behaviour? If not, what is the correct behaviour, according to the C++ Standard?

I have a recollection from previously discussing on SO that all cases should write 0 since C++11, but I could not find anything using the search feature; and the iostreams section of the C++ standard is pretty heavy going.

Aucun commentaire:

Enregistrer un commentaire