Endless Loop need help

Hi all,

I am learning C++ programming. The following works so far, but if a non int is entered the code loops continuously with Input Error, Try Again.... Why does it loop and never rehit the cin?

Much Appreciated.

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
source.h
#pragma once
#include <iostream>

using namespace std;

int input;						
bool isGameRunning = true;		
int main();

source.cpp
						
int main()
{
	cout << "Welcome to the Game" << endl << endl;
	cout << "Main Menu" << endl;
	cout << "---------------------" << endl;
	cout << "1. Start New Game" << endl;
	cout << "2. Load Saved Game" << endl;
	cout << "3. Options" << endl;
	cout << "4. Quit" << endl;
	cout << "---------------------" << endl << endl;
	cout << "Select 1-4: ";
	cout << endl;

	while (isGameRunning)
	{
		cin >> input;

		if (cin.fail()) 
		{
			cout << "Input Error, Try Again... " << endl;
		}
		else
		{
			switch (input)
			{
			case 1:
				cout << "Starting New Game... " << input << endl;
				break;
			case 2:
				cout << "Loading Saved New Game... " << input << endl;
				break;
			case 3:
				cout << "Entering Options... " << input << endl;
				break;
			case 4:
				isGameRunning = false;
				break;
			default:
				break;
			}
		}
	}

	//Exit Game
	return 0;
}
The easiest way to fix this error is to make your input a double or float type.
Hi,

You can let the default: case of the switch catch the error, but you will need:

1
2
cin.clear(); 
cin.ignore(std::numeric_limits<int>::max(),'\n');


WakeofMisery wrote:
The easiest way to fix this error is to make your input a double or float type.


How does that make any sense at all?
Last edited on
He's saying that a "non int is entered." I was just assuming he meant 3.5, 29.21, etc.
TheIdeasMan,

Thanks for the tips, I'll definitely look at implementing this into the switch statement as it looks more tidy. I was just wondering why it loops as coming from a c# background this would work, but after some reading your solution and then this post http://www.cplusplus.com/forum/beginner/2957/ that I found i now understand that buffer was not cleared so cin.fail() would always be true until i repaired it.

Thanks so much guys.

Modified while loop
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
	while (isGameRunning)
	{
		cin >> input;

		switch (input)
		{
		case 1:
			cout << "Starting New Game... " << input << endl;
			break;
		case 2:
			cout << "Loading Saved New Game... " << input << endl;
			break;
		case 3:
			cout << "Entering Options... " << input << endl;
			break;
		case 4:
			isGameRunning = false;
			break;
		default:
			cout << "Input Error, Try Again... Input was " << input << endl;
			cin.clear();
			cin.ignore(std::numeric_limits<int>::max(), '\n');
			break;
		}
	}
Last edited on
Topic archived. No new replies allowed.