Input causing infinite loop..

Program asks for a 1 - 3 input.
And it supposed to display an error for anything else including letters etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

do {
cout << "Option: "<< endl;
cin >> option;



		switch (option)
		{
		case 1:cout << "Explanation";

		case 2:
		break;

		case 3:exit(1);


		default:cout << "ERROR" << endl;
                        cout << "Press ENTER to continue." << endl;
		        cin.ignore();
			cin.get();
		}
}while (!(option >=1 && option <=3));



The code is just rough because i just cut out alittle portion of the program and took out some pieces to make it easier on the eyes.But it seems to catch incorrect numbers but any letters are causing an infinite loop. I tried catching a possible new line character stuck in the stream but i can't seem to figure it out.
Last edited on
You forgot to break; out the loop. When you do not break, it will not exit the loop, and will continue until it finds a break.

This probably explains:
http://www.learncpp.com/cpp-tutorial/53-switch-statements/

It's a painful error that the compiler does not detect, but generally you won't be making it. At least in my opnion, but lots of people think it's a common error.
It can be useful, too. I will not cite examples though.
Last edited on
Even with the breaks , a value such as "i" entered will cause an infinite loop.

Appreciate the input on the issue though.
Last edited on
I cant see the variable type of option, but if it's an int, double, float, long, or short, then it won't accept characters. When you try to put a character into an int, the program will go crazy.

You could try using a char and making the cases case '1': case '2': and case '3':
Try using if-else.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
do {
cout
cin >> option;

if (1)
do that

else if (2)
do that

else if (3)
do that

else
error
} while (!(option >=1 && option <=3));


This is just a rough mock up. I've actually edited the part of your code and it works.
Didn't put in case you wanted to try it out on your own. By doing the if-else does work.
Just ask if you'd like me to just paste what I made.
Last edited on
Topic archived. No new replies allowed.