You should do error checking on std::cin
if the value you are reading is as you would have expected, otherwise std::cin
fails and the value of i
is set to 0
:
#include <iostream>
int main()
{
int i;
if(std::cin >> i)
{
std::cout << i << std::endl;
}
else
{
std::cin.clear();
std::cout << "No integer" << std::endl;
}
return 0;
}
You can also handle the error detection using a while
loop. An example could be like below:
#include <iostream>
#include <limits>
int main()
{
int age { };
// executes the loop if the input fails or is out of range (e.g., no
// characters were read)
while ( ( std::cout << "How old are you? " ) &&
( !( std::cin >> age ) || age < 1 || age > 200 ) )
{
std::cout << "That's not a number between 1 and 200; ";
// clear bad input flag
std::cin.clear();
// discard bad input
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
std::cout << "You are " << age << " years old.\n";
}
Sample input/output:
How old are you? a
That's not a number between 1 and 200; How old are you? #12gj
That's not a number between 1 and 200; How old are you? foo
That's not a number between 1 and 200; How old are you? 84
You are 84 years old.