I wouldn't label this as a 'noob' question. If it was truly a 'noob' question then your thread would be flooded with answers and suggestions by now. This isn't something easy to achieve, I myself struggled for weeks back when I was learning C++ to bring about something like this.
Your attempt to accept only integer values from the user is good, but as you said, it wouldn't work quite well if the user entered a digit followed by random gibberish. So here's my suggestion, why don't you declare
userInput
as a string instead of integer. Then, what you could do, since a string is essentially an array of characters, you could loop through each individual element in the string and check whether it's a character or not. Something like this:
1 2 3 4 5 6 7 8 9 10 11 12
|
string text;
LABEL:cin >> text;
for (int i = 0; i < text.size(); ++i)
{
if (!(isdigit(text[i])))
{
cout << "Incorrect input. Please enter a proper integer value.\n";
cin.clear();
cin.ignore(256, '\n');
goto LABEL; //NOTICE: This will go up 12 lines
}
}
|
The user will be prompted to enter another value should the loop detect a non-digit character. Then, you could do something like
|
int aNumber = stoi (text); //Converts text into integer.
|
- OR -
|
float aNumber = stof (text); //Converts text into float.
|
Hope you found this helpful.
EDIT: If you're one of those "we mustn't use
goto
as they lead to confusion" guys, then use
break;
and figure out the rest.