Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this while loop not ending in the code below?

Sorry, this code seems silly but I just want to get the logic.

I am trying to end the program when the user enters quit as an input.

I wrote name != "quit" && sname != "quit" as the while condition, so if any of them is quit, the loop would end (right?).

But when I write quit as name, it still waits for sname input, if I write quit also for the sname input, then it finally ends. But shouldn't it end when it see quit for the very first time since I wrote the conditions with &&?

In addition, I get the same output when I wrote the condition with ||. Why is this so?

    int main()
    {
        string name="",sname="";
        cout << "enter your name and surname \n";

            cout << ">>name=";
            getline(cin,name);

            cout << ">>surname=";
            getline(cin,sname);

       while (name != "quit" && sname != "quit")
        {
            cout << ">>name=";
            getline(cin,name);

            cout << ">>surname=";
            getline(cin,sname);
        }

        return 0;
    }

Output:

enter your name and surname
>>name=John
>>surname=Wick
>>name=quit
>>surname=
like image 501
noobie Avatar asked May 21 '26 04:05

noobie


2 Answers

Good question! This has to do with how while loops work.

In C++, a while loop works as follows:

  • First, it checks if the condition in the parenthesized statement in the while loop is true.
  • If so, it executes the entire body of the while loop, then jumps back to that first step.

In other words, a while loop won't stop running as soon as the condition is false. Rather, it stops running once it gets to the point where it reevaluates the condition and finds that it's false.

This is why it doesn't matter whether you're using && or || here. The loop won't exit until the condition gets checked again, and that won't happen until the current loop iteration finishes running.

This leaves you with a few options about what to do.

  1. You could add an explicit check into the while loop after reading the first string to confirm that the string isn't "quit", only executing the rest of the loop if you need to.

  2. You could add a break statement into the middle of the loop to tell the loop to stop running. This might be done in combination with option (1).

Hope this helps!

like image 173
templatetypedef Avatar answered May 23 '26 18:05

templatetypedef


In the while loop, it's doing a check every time after inputting both first name and surname, that means it will only check after you enter the surname as well. You can do this:

while (true) {
    getline(cin, name);
    if (name == "quit") break;
    getline(cin, sname);
    if (sname == "quit") break;
}

something like that. :)

like image 45
David W Avatar answered May 23 '26 18:05

David W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!