you could use cin.fail() but then you also have to use cin.clear() and cin.ignore(500,'\n') somewhat like this
1 2 3 4 5 6 7 8 9 10 11
int c;
start:
cin>>c;
if(cin.fail())
{
cout<<"\nplease enter a int\n";
cin.clear();
cin.ignore(500,'\n');//500 is just a large number nothing special about it
goto start;
}
Example program showing basic useful stuff like looping on input and stream state manipulation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <limits>
int main()
{
int x;
std::cout << "Enter a number\n";
while(not (std::cin >> x)) { //while error flag is set after input
std::cout << "Invalid input\nPlease enter a number\n";
std::cin.clear(); //clear error flags
//skip all characters currently in buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "You entered " << x;
}
If you want to tighten up the input code so the user is not allowed to enter values like "78kg" "99 red balloons", or "1 2 3 4", then it takes a bit more effort.
#include <iostream>
#include <sstream>
#include <limits>
int main()
{
int x = -1; // something other than 0
do {
bool notDone = true;
while (notDone) {
std::cout << "Enter a number (0 to quit)\n";
std::string line;
std::getline(std::cin, line); // read whole line
std::istringstream is(line); // use string to init stringstream
// try to extract an int (x) and, if successful, any non-whitechar
// later on the line (should get just the int)
char dummy = '\0';
// if we fail to get an int or we successfully get something other
// than whitespace
if (!(is >> x) || (is >> std::ws && is.get(dummy)))
std::cout << "Invalid input. Try again!\n";
else
notDone = false ;
}
std::cout << "You entered " << x << "\n";
} while(0 != x);
return 0;
}
Enter a number (0 to quit)
68kg
Invalid input. Try again!
Enter a number (0 to quit)
99 red balloons
Invalid input. Try again!
Enter a number (0 to quit)
1 2 3 4
Invalid input. Try again!
Enter a number (0 to quit)
42
You entered 42
Enter a number (0 to quit)
0
You entered 0
#include <iostream>
#include <limits>
int main()
{
int x = -1; // something other than 0
do {
std::cout << "Enter a number (0 to quit)\n";
while(not (std::cin >> x)) { //while error flag is set after input
std::cout << "Invalid input\nPlease enter a number\n";
std::cin.clear(); //clear error flags
//skip all characters currently in buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "You entered " << x << "\n";
} while(0 != x);
return 0;
}
Enter a number (0 to quit)
68kg
You entered 68
Enter a number (0 to quit)
Invalid input
Please enter a number
99 red balloons
You entered 99
Enter a number (0 to quit)
Invalid input
Please enter a number
1 2 3 4
You entered 1
Enter a number (0 to quit)
You entered 2
Enter a number (0 to quit)
You entered 3
Enter a number (0 to quit)
You entered 4
Enter a number (0 to quit)
42
You entered 42
Enter a number (0 to quit)
0
You entered 0