“How do I flush input” is a distressingly common question.
The answer is
don’t.
The causes of the problems that tend to cause this question have nothing to do with wiping the user’s (valid) input. They are because there is something wrong with the way you are processing it.
You have made a couple of mistakes in understanding here.
The first is that you want to skip all the stuff that the user typed after their first initial, so you thought to use
cin.ignore()
. (Good job!)
The problem was that you decided to delimit on a space — something the user
never input (first name will not likely have a space in it).
So your code, not finding a space, keeps you waiting until 20 inputs are received (which seems random, because you are skipping characters without processing, and on Windows systems, a newline is
two characters...).
Then you ask for a single character, which I presume was to rid yourself of the newline.
Remember the cardinal rule of user input:
The user will always press Enter after every input request.
So, what you should have done is get the first letter, then just ignore everything up to and including the Enter key press that the user gave you.
1 2 3 4 5
|
// Skip leading whitespace, get the first letter of the user's name (presumably)
cin >> ws >> firstNameInitial;
// Skip all remaining letters (and anything else) until EOL
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
|
Next, watch your logical conditions. If you want to make sure the user input a letter in 'A' .. 'Z', BOTH conditions must hold:
1 2 3 4 5 6 7 8
|
if ((userAlpha >= 'A') && (userAlpha <= 'Z'))
{
cout << "Good job! You entered the majuscule '" << userAlpha << "'!\n";
}
else
{
cout << "Hey! That's not what was asked for!\n";
}
|
Also, you need to be explicit. The user could have entered a lowercase letter and still been strictly complying with your instructions. Be clear!
1 2 3 4 5 6
|
char c;
cout << "Please enter a letter of the alphabet: ";
cin >> c;
if (isalpha( c ))
...
|
If you require the character to be only majusucle, convert it yourself:
I STILL have to enter my response of the alphabetical letter TWICE, though in my code, it doesn't seem to have that. What could be the problem? |
The problem is that your code says to ask the user for something twice.
As already noticed, the condition lets any letter through, and then you say
cin >> userType;
, which makes the program want input — even though you didn’t warn the user that it would be required.
Getting your head around these logical issues takes time.
Don’t get discouraged, you’ll get there soon.
Good luck!