Cin in a while loop

后端 未结 5 922
南笙
南笙 2021-01-25 08:00

So, I\'ve looked around and haven\'t been able to figure out what\'s going on with cin during my While loop. I\'m working through the book C++ Primer (5th edition) and I noticed

5条回答
  •  太阳男子
    2021-01-25 08:43

    Hitting Enter produces either a CR or LF or both, depending on your platform. This is a valid input so satisfies the condition to continue the while loop. You will need to either explicitly test for these characters at the beginning of your input or use Ctrl-C to break out of the loop.

    As a readability issue, I would include braces around the code that you want in the loop. What you have there is valid C++ since without braces the while will loop on the next statement and the whole if conditional is a single statement. Practice putting them in now even on single line loops and you'll save yourself some headache debugging in the future.

提交回复
热议问题