I'm writing a trivia game program that gives a menu of options. The way I organized it, the user inputs a value (read into the variable int user_input), and the program does something based on that. The problem comes when the user inputs a character - the program just enters an infinite loop. What can I do to stop this?
Here's the code (well, some of it. I cut out from the beginning and the end, but I'm assuming just about everything but the while() loop is irrelevant.)
(As I said, user_input is an int, not a char, as it probably should be. But I'd rather not rewrite a big chunk of my program.)
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
bool GetInt(int & n)
{
string str;
getline(cin,str);
stringstream buffer(str);
buffer >> n;
if (!buffer)
{
cout << "non numerical data!" << endl;
returnfalse;
}
if (!buffer.eof())
{
cout << "buffer not consumed!" << endl;
returnfalse;
}
returntrue;
}
int main()
{
int my_int;
while (true)
{
cout << "enter an int (0 to quit): ";
if (!GetInt(my_int))
{
cout << "you did not enter an int..." << endl;
}
else
{
cout << "you entered an int!" << endl;
if (my_int==0)
{
cout << "ok, bye!" << endl;
break;
}
}
}
cout << "\n(hit enter to quit...)" << endl;
cin.get();
return 0;
}
enter an int (0 to quit): 123
you entered an int!
enter an int (0 to quit): asdf
non numerical data!
you did not enter an int...
enter an int (0 to quit): 123asdf
buffer not consumed!
you did not enter an int...
enter an int (0 to quit): 0
you entered an int!
ok, bye!
(hit enter to quit...)
I have a similar problem. The way I thought to solve it was to use a string temp and then check that that was an integer then convert and assign that string to the correct int variable. However I'm having trouble with checking and converting the string.
Since you are using single digits I would think about switching to char as mentioned above to give you better control.