Home > front end >  Ending a while loop in command prompt
Ending a while loop in command prompt

Time:12-01

This is an excerpt from the Result

CodePudding user response:

In order for that loop to end, cin needs to enter a failed state. That will cause it to evaluate to false and stop the loop. You have a couple ways you can do that. First is to send bad input, which will cause cin to fail and end the loop. Since you are excepting integers, you could just input a letter and that will cause it to break.

Another option is to send the EOF (end of file) signal to cin You can do that using ctrl D (windows) or ctrl Z (linux) and the pressing enter. cin will stop reading once it sees it has reachged the EOF and it will enter a failed state and cause the loop to end.

It should be noted that with both of these options that if you want to use cin again after you do this you will need to call clear() to remove the error flags and if you entered bad input, you will need to use ignore() to remove the bad input from the stream.

CodePudding user response:

My question is how do we end such a loop in the command prompt, where the prompt takes one input at a time?

Note that cin >> x; returns cin. This means when you write

while(cin >> x)

you do the >> operation into x and then check cin.

When the user enters an input whose type differs from the type of variable x, then this while loop will end automatically. This is because cin will not be in a valid state anymore and hence cin >> x will become false . Basically the loop ends when the state of the stream is set to failed. Like supplying a different type value or when EOF is encountered.

There is other way to end such a loop from inside the while block by using break .

  • Related