While loop breaks unexpectedly

Jul 4, 2015 at 6:56am
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 Jul 4, 2015 at 6:56am
Jul 4, 2015 at 8:09am
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.
Jul 5, 2015 at 12:03am
I suggest you remove the cin>> statements out of the curly braces, let them be on their own.
Jul 5, 2015 at 3:34am
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.