Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ending a while loop in command prompt

This is an excerpt from the Competitive Programmer’s Handbook by Antti Laaksonen:

If the amount of data is unknown, the following loop is useful:

while (cin >> x) {
// code
}

This loop reads elements from the input one after another, until
there is no more data available in the input.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My question is how do we end such a loop in the command prompt, where the prompt takes one input at a time? By pressing enter, the prompt asks for new input and not terminating the input.

Edit: I have tried using ctrl + D/Z but I am getting this:
Result

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading