unexplained infinte loop? code analysis needed

I have been making a Guess My Number game, and I was seeing what would happen if I changed some of my answers a little, so for difficulty I put 'n', instead of the 1, 2 or 3 that I should normally use. It then set itself on an infinite loop for some apparently unexplained reason.

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
 startLabel:
    cout << "\tWelcome to Guess My Number!\n\n";
    difficultyLabel:
    cout << "Difficulty:\t 1 - Easy\t 2 - Normal\t 3 - Hard\n\n";
    cin >> difficulty;

    switch(difficulty)
    {
    case 1:
        cout << "\nEasy: ";
        maxNum = 50;
        cout << "Number will be generated between 1 and 50.";
        break;
    case 2:
        cout << "\nNormal: ";
        maxNum = 100;
        cout << "Number will be generated between 1 and 100.";
        break;
    case 3:
        cout << "\nHard: ";
        maxNum = 200;
        cout << "Number will be generated between 1 and 200.";
        break;
    default:
        cout << "\nYou made an invalid choice.\n";
        cout << "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n";
        goto difficultyLabel;
    }


I'm still fairly new to C++ so I realise my question may be pretty stupid, but help would be much appreciated :D

Edit: I should probably add that when I put the difficulty as another number, for example 4, it just repeats and asks for difficulty again like it should do.
Last edited on

It will do that as its expecting a numeric value and your giving it a ascii character. You should also try and avoid goto statements, not good practice - use a do..while to make sure they enter within the range required so you dont need that nasty goto statement ;-)

Anyway, to get around the loop issue just read in a character and test that instead of an int.

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

#include <iostream>
using namespace std;

int main()
{
	char difficulty;

	do {

		cout << "Difficulty:\t 1 - Easy\t 2 - Normal\t 3 - Hard\n";
		cin >> difficulty;

	} while (difficulty < '1' || difficulty > '3');

	switch (difficulty)
	{
		case '1':
			// code here...
		break;
	}

	return 0;
}
Do reaserch on cin.ignore and cin.clear functions to defend your code against user accidentally typing text where numeric value is expeced.
Topic archived. No new replies allowed.