Char Input Validation.

Hey guys, I'm having a bit of trouble making sure the user can't input anything other than 'Y', 'y', or 'N', 'n' for a Yes or No question.

My code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
cout << "Rent this game? (Y/N)." << endl;
			cin >> YesorNo;

		cout << string( 2, '\n' );

		while (isdigit(YesorNo) || ispunct(YesorNo))
		{
		cout << "ERROR: Invalid input!" << endl; 
		cin.clear();
		cin.ignore(100, '\n');
			cin >> YesorNo;
		}

		if (YesorNo == 'Y' || YesorNo == 'y')
		{
		Checkout();
		}

		else if (YesorNo == 'N' || YesorNo == 'n')
 
		ClearScreen(); // CALL FUNCTION THAT PRINTS x15 NEW LINES.
		cout << "You have been returned to the main menu." << endl; 
		cout << string( 3, '\n' );

		break; // AFTER THIS BREAK A MENU LOOP WILL OCCUR. 


So basically what I have here is a YesorNo variable and a while loop that displays an error if the input happens to be a number or punctuation (such as -1).

This works great so then my code proceeds to the if 'Y' or 'y' validation which works great as well. In addition my if 'N' or 'n' works too.

What doesn't work is if the user inputs any other letter than 'Y', 'y', 'N' or 'n' such as an a, b, c, d, etc. I'm not sure what else I can put in there to further solidify the input validation.

My program fails and continues with the rest of the code thus looping the program as seen in one of my comments above as if 'N' or "n' was inputted.

Any ideas to get good validation here? Thank you.
Last edited on
This should work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cctype>
int main()
{

	std::cout << "Please enter [Y/N]: ";
	char yesOrNo;
	std::cin >> yesOrNo;

	yesOrNo = toupper(yesOrNo);

	while (yesOrNo != 'Y' && yesOrNo != 'N')
	{
		std::cout << "Error invalid input please try again " << std::endl;
		std::cout << "Please enter [Y/N]: ";
		std::cin >> yesOrNo;
		yesOrNo = toupper(yesOrNo);
	}


	std::cout << "You entered " << yesOrNo << std::endl;

	return 0;
}
Yup! That works! VERY nice code you just wrote up there, I like your use of toupper and !=.

I added cin.clear(); and cin.ignore(100, '\n'); though to avoid multiple prints of the cout error.

Thank you! (=

Topic archived. No new replies allowed.