FailCheck a Char.

So I'm trying to write a fail check for a char data type so that in case a user inputs a word then it will deny it then send an error and ask for another input. However everytime it is ran it poops out the cout message as many times as there were characters in the word due to the loop. I only want it to display the message once for every enter. Here's how the function looks in my code:


1
2
3
4
5
6
7
8
9
char charfailSafe(char Choice)
{
	do
	{
		cout << "That is not a valid choice (Y/N): ";
		cin >> Choice;
	} while (Choice == 'y' || Choice == 'Y' || Choice == 'n' || Choice == 'N');
	return Choice;
}
Last edited on
6
7
		cin >> Choice;  // Get one character
		cin.ignore(numeric_limits<streamsize>::max(), '\n');  // Ignore the rest of the line 

Don't forget to #include <limits> .

Hope this helps.
or, read a full line into a string and check its length, if its > 1, complain and repeat.

If you read a full line, though, be careful to account for leading whitespace.

6
7
8
9
		string s;
		getline( cin >> ws, s );
		if (s.size() != 1) ...
		Choice = s[0];

This just seems like a lot of extra work...
all 3 ideas behave slightly differently. I was going off the idea that anything not exactly 1 char is invalid. "fail check for a char data type so that in case a user inputs a word then it will deny it"
I would personally consider leading whitespace as invalid too, but its subjective, requirement isnt exactly up to industry standards! I say he should send it back to his requirements team and take the rest of the day off.
Last edited on
Topic archived. No new replies allowed.