PHP中文网2017-04-17 14:26:53
This code will keep looping to test whether the input stream is normal until the input stream reaches the end of the file, or an error occurs in the input stream.
Shouldn’t the expression in while brackets result in a bool type? Why can it be an input statement?
while括号中的表达式的确是bool类型,所以你可以纠结一下 `cin >> n`这个表达式的返回值到底是什么(`>>`正常读取,返回的是cin的地址值;读入错误时,则返回0)
Q: Then how does it jump out? Is it possible to break out of the loop only when the input number is 0?
跳出循环的两种输入方式:
windows下 `ctrl+z`
linux下 `ctrl+d`
Yeah. . . . In fact, I don't know much about it, but what I am more troubled about is what you said "can't find". If you really can't find the answer, I want to share my experience.
First of all, for a senior novice like me, I have always firmly believed that there are only unimaginable novice questions and no answers that cannot be found.
Then, you can check whatever you want. For example, for this question, you can ferry it around while(cin>>n)
and you will find a bunch of answers you want (eg. when can you break out of the loop);
Then, if you are not only obsessed with when to stop, but also consider the expression value, you can check the return values of while
and cin >> n
to see what secrets are hidden.
It’s easy for beginners to do it, but it’s obviously not as interesting as tracing back a problem layer by layer by yourself (this is to encourage myself XD)
Another great answer to share: cin, cout, and their return values