While loop breaks unexpectedly

I still couldn't figure out the solution to my problem in my Dungeon Crawler program, so I decided to test something more basic.

Here is the same problem: If I keep pressing the same number (like 5 to 5 over and over), the program works.

BUT, if I switch to a different number on the 3rd loop (like 5 to 9, and back to 5), the program just stops instead of producing the proper print statement for 5. Why is this happening?

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

int main()
{
    cout << "Hello world! Enter a number" << endl;
    int x;
    cin >> x;

    while (x == 5)
    {
        cout << "Try again, you got 5" << endl;
        std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        cin >> x;
    }
    while (x == 9)
    {
        cout << "You got 9, try again mate" << endl;
        std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        cin >> x;
    }


    return 0;
}
Last edited on
After loop 9-14 is done (number is not 5) you will never return to it again. So when the second loop is done (number is not 9), program will continue executing from line 21. And there is nothing but "end the program" statement.
I suggest you remove the cin>> statements out of the curly braces, let them be on their own.
I think this is what you want.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
while (x != 0)  // zero to exit the loop
    {
    if (x == 5)
        {
        cout << "Try again, you got 5" << endl;
        std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
       }
    else if (x == 9)
        {
        cout << "You got 9, try again mate" << endl;
        std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        }
     cin >> x;
     }
Topic archived. No new replies allowed.