HoHhoch HoHhoch - 3 years ago 120
C++ Question

Loop repeats indefinitely after break (c++)

My problem here is when the loop is broken after the user indicates they're done, the program then begins to print the last input infinitely. What's going on here? I've tried using break, return 0, setting loop = a, all results in the same thing. On a program earlier I used a for loop (used break) and it terminated just fine.

Note: This post is NOT up for syntax corrections, this is just a fragment, and the code runs fine until I terminate the loop. I'm wanting to know what's causing this to happen with a while-loop specifically.

Edit: Nevermind, figured out what was going on. When attempting to end the loop there was a datatype error (as you can see, we only receive input for two variables, both of which are ints), which caused the loop to the start repeating the last valid datatype entered. So my question is why does this happen with a data type error?

while (loop != "a")
cout << "Enter the first number: ";
cin >> input1;
cout << "\nEnter the second number: ";
cin >> input2;

cout << input1 << '\t' << input2 << '\n';

if (loop == "|")

Answer Source

It might be because you entered a wrong data type into 'cin'. This makes cin fail and it repeats the last acceptable value in the command prompt. Nothing to do with the loop. If you try it outside of the loop you'll see the same thing happen.

It's good practice to do the following:

while (!(cin >> input))
    cin.ignore(256, '\n');
    cout << "Bad input. Try again: ";

so if cin fails - it will clear the fail status, ignore the last input and ask the user to enter his input again.

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download