In the following program I ask a user to input a number which is greater than zero and from there the computer lists all numbers from 1 to that number.
For example, if the user entered 5, the program would output:
1
2
3
4
5
I'm trying to dummy proof the program so that if the user entered a letter for example, it would return an error and loop back to the prompt for the input again. For some reason this won't work though, and the console just continually outputs the error if the input is bad, forcing me to crash the program to quit it.
#include <iostream>
using namespace std;
int main()
{
int x = 0;
while (x <= 0)
{
//prompt user for input
cout << "Please enter an integer greater than zero: ";
cin >> x;
//if input is not a number, or is less than or equal to zero, return an error
//(this doesn't work if the input isn't a number)
if (cin.fail())
{
cout << "Error: Please enter an integer." << endl;
x = 0;
cin.clear();
}
else if (x <= 0)
{
cout << "Error: Please enter an integer greater than zero." << endl;
}
}
//outout numbers between 1 and input (this is functioning)
for (int i = 1; i <= x; i++)
{
cout << i << endl;
}
//alert user and terminate program
cout << "End of program. Exiting..." << endl;
return 0;
}
Could someone please explain to me the best way to go about this? i.e. to catch the input and detect if it is invalid? I thought cin.bad()
would do the trick, but I guess not?
Update: using cin.fail()
still results in the looping of my error output.
I also forgot to mention that I am relatively new to programming in C++, so I'd like to apologise if I don't understand something right away.