Having some problems with input

im using a user-inputeed int to send into a switch statement in a menu system that i am using. however if the user enters a string or char by accident my program goes into an endless loop. please can someone tell me how to guard against this?

ive got so far:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
void Menu:: menu()
{	
	top:
	int choice = 0;
	cout << "====" << endl;
	cout << "MENU" << endl;
	cout << "====" << endl;
	while(choice >= 0)
	{
		cout << endl;
		cout << "Pick an option." << endl;
		cout << "1. Create Customer." << endl;
		cout << "2. Find Customer." << endl;		
		cout << "3. Print All Customers" << endl;
		cout << "4. Accounts." << endl;
		cout << "10. Exit." << endl;
		
		cin >> choice;
		if(!isdigit(choice))
		{
			cout << "Choice must be an integer" << endl;
			cin >> choice;
			goto top;
			
		}
		if (choice > 0 && choice < 5)
			{
				choices(choice);
			}
		else if(choice == 10)
			{
				choice = -1;
			}
		

		else
			{
				cout << "Invalid choice." << endl;

			}
	}

}


but when the user inputs a string/char it still goes into an infinite loop, although i can make out that its still going to the top where its supposed to but then looping again n again.

any help will be greatly appreciated

//EDIT:

ive just had to take out:

1
2
3
4
5
6
7
if(!isdigit(choice))
		{
			cout << "Choice must be an integer" << endl;
			cin >> choice;
			goto top;
			
		}


as it causes the infinite loop when i actually need to enter strings in another section of my code
Last edited on
you can use a 'string' variable that is used to get the inputfrom user, then check valid input with isdigit(). if valid, you can use atoi() function to get an integer from a const char* (you can use string.c_str() to get it).
Topic archived. No new replies allowed.