When the input will stop?

自古美人都是妖i 提交于 2021-01-28 06:58:00

问题


Hi guys i have the following question:

string s;

std::cout << "give me a string" << std::endl;  
while (std::cin >> s){
    std::cout << "give me a string" << std::endl;
}
cin.clear();  

if s was an integer then i know that if i typed a char then the while would break. If it was an integer and typed a double the same would happened. But what about strings ?? Somewhere I read that in windows (as I am writting at netbeans in windows) you have to press ctrl+z and then it stops as it is taken as a false string. But when i do this , the process freezes and nothing happens.


回答1:


You need to send the EOF signal, which in Netbeans is Ctrl + D.

However, hitting Enter twice will result in the condition of your loop to resolve in false, causing the loop to stop. That's excpected: How is "std::cin>>value" evaluated in a while loop?

If that doesn't work, use Ctrl + z and a newline character, which is the EOF signal in Windows, as stated here. Ctrl + D is for Linux though, but it works in your case.

The EOF signal closes the input stream, thus breaking the loop.


Moreover, in Netbeans (if the above doesn't work) it seems that you need to run your application from the command prompt to achieve this. Another attempt would be to "press Ctrl + z after pressing Enter", as stated here.




回答2:


The loop will stop when the input stream is closed.

If you run the program from a shell, then the input stream may be open indefinitely. Exactly how you would close the stream in a terminal, depends on what terminal you are using.

In UNIX, the stream is closed when you send empty input. ctrl + d is the standard key combination for sending (flushing) the input to the stream (^d is the ASCII control code EOT, end of transmission). Pressing enter also sends the input, but it also inserts the end of line character, so it is not possible to use it to send empty input.

ctrl + z is similar in windows, but it has different behaviour (wikipedia):

The EOT character in Unix is different from the Control-Z in DOS. The DOS Control-Z byte is actually sent and/or placed in files to indicate where the text ends. In contrast the Control-D causes the Unix terminal driver to signal the EOF condition, which is not a character, while the byte has no special meaning if actually read or written from a file or terminal.



来源:https://stackoverflow.com/questions/46114870/when-the-input-will-stop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!