Limit Input

I am trying to limit the following code to only allow / read one char of input.

If you type in, say 3333, it will display the error message 4 times.

I am looking for a better way to solve this or to just limit the cin >> choice to only read the first digit / variable the user inputs.

Thanks in advance for your help!

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
26
	do
	{ // start loop
		cout << "\nPlease Enter 1 for 1st of Month Bills or 2 for Mid Month Bills <Q to Quit>: ";
		char choice;
		choice = 0;
		cin >> choice;
		
		if (choice == 'q' || choice == 'Q')
		{
			cout << "\nGood Bye\n\n";
			break;
		}
		else if (choice == '1')
		{
			FirstMonthBills ();// call / invoke this function for choice 1
		}
		else if (choice == '2')
		{
			MidMonthBills (); // call / invoke this cunction for choice 2
		}
		else
		{
			cout << "\nError! Your Choices Are:\n\n1 for 1st of Month Bills\n\n2 for Mid Month Bills\n\n<Q to Quit>" << "\n\n";
		}
	}	while (choice != 'Q' || choice != 'q'); // end loop
} // end main 
Would this work?

1
2
3
4
5
6
7
8
include <limits>
//... 
else
{
	cout << "\nError! Your Choices Are:\n\n1 for 1st of Month Bills\n\n2 for Mid Month Bills\n\n<Q to Quit>" << "\n\n";
	cin.ignore( numeric_limits<int>::max() , '\n' );
}
//... 
Thanks, that does stop the multiple errors from happening (can you explain the code please?) ....

but

Now whenever I enter 123 (or similar beginning with 1) it invokes the FirstMonthBills () function

or

If I enter 256 (or similar beginning with 2) it invokes the MidMonthBills () function.

Updated 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
26
	do
	{ // start loop
		cout << "\nPlease Enter 1 for 1st of Month Bills or 2 for Mid Month Bills <Q to Quit>: ";
		char choice;
		choice = 0;
		cin >> choice;
		
		if (choice == 'q' || choice == 'Q')
		{
			cout << "\nGood Bye\n\n";
			break;
		}
		else if (choice == '1')
		{
			FirstMonthBills ();// call / invoke this function for choice 1
		}
		else if (choice == '2')
		{
			MidMonthBills (); // call / invoke this cunction for choice 2
		}
		else
		{
			cout << "\nError! Your Choices Are:\n\n1 for 1st of Month Bills\n\n2 for Mid Month Bills\n\n<Q to Quit>" << "\n\n";
			cin.ignore( numeric_limits<int>::max() , '\n' );
		}
	}	while (choice != 'Q' || choice != 'q'); // end loop 
Last edited on
Topic archived. No new replies allowed.