Can you please tell us how best to check the variable for overflow when entering it from the console

For example for the code

int i; cin >> i; cout << i << endl; 

Available: enter image description here

  • Enter as a string and check ... - Harry
  • Thank you, I got it =) - Leerg319
  • True, I have a difficult way to check through ... In my program, I have to read a number into an int, translate it into a string, check if it fits in int, then fit, back to int ... Maybe there is something simpler? PS I decided to check by translating INT_MAX into a string and comparing what I entered with it, not forgetting the minus. - Leerg319

2 answers 2

The error can be determined either through the good () function or simply by checking the stream in the conditional statement. But after determining that an error has occurred, it is necessary to remove errors from the stream using the clear () and ignore () functions, otherwise the subsequent input will not work:

 int a; cout<<"Input a="; cin>>a; if( cin.good() ) // if ( cin ) { cout<<"Correct input a="<<a<<endl; } else { cout<<"Error input"<<endl; cin.clear(); cin.ignore(); } int b; cout<<"Input b="; cin>>b; cout<<"b="<<b<<endl; 

An example of the result of the program: Input Validation

If you remove the clear, the lines clear () and ignore (), then the subsequent input to the variable b flies without stopping. An example of such work: No cleaning

    Solved the problem using after checking input

     if (cin.good()) 
    • Yes, but this is not just overflow, but you asked about it. - Harry