Should C ++ keep variables unchanged when input fails?

Does C ++ guarantee the integrity of variables when input fails? With older versions of gcc, such a program retains the value i in case of an error i (for example, if a letter is entered instead of input on the input). With Ubuntu 10.10 (gcc 4.4.5), I reset to zero if input fails.

#include <iostream>

int main()
{
 int i = -1;
 std::cin >> i;
 std::cout << "i = " << i << '\n';
 return 0;
}

This behavior breaks a lot of my code. I believe that gcc people know what they are doing, and that will probably be my mistake. If someone knows the standard, I would like to know what he says about this situation.

Thank.

+3
source share
3 answers

Do not rely on a variable. Rely on the state of the thread:

if (std::cin >> i) // "if (!std::cin.fail())" would also work
{
    // ok
}
else
{
    // error
}


, , ++:

++ 03:

, val ; .

++ 0x (... ):

, , :

  • 0, .
  • ( ) , ( ), .
  • , , , .
  • , .
+5

++ . [lib.facet.num.get.virtuals] (22.2.2.1.2 ++ 03, 22.4.2.1.2 ++ 0x)

++ 03 , .
++ 0x , 0 .

+3

, , , , , , , .

istringstream.

+1

Source: https://habr.com/ru/post/1770314/


All Articles