如何表示循环中不再有字符串 ss 的输入 while (cin >> ss)

2021-12-29 00:00:00 file-io eof c++ cin

我使用cin"从输入流中读取单词,例如

I used "cin" to read words from input stream, which like

int main( ){
     string word;
     while (cin >> word){
         //do sth on the input word
     }

    // perform some other operations
}

代码结构与上面类似.它是可编译的.在执行过程中,我不断输入类似

The code structure is something like the above one. It is compilable. During the execution, I keep inputting something like

aa bb cc dd

我的问题是如何结束这个输入?换句话说,假设文本文件只是aa bb cc dd".但是我不知道如何让程序知道文件结束了.

My question is how to end this input? In other words, suppose the textfile is just "aa bb cc dd". But I do not know how to let the program know that the file ends.

推荐答案

您的代码是正确的.如果是交互式输入,则需要发送 EOF 字符,例如 CTRL-D.

Your code is correct. If you were interactively inputting, you would need to send a EOF character, such as CTRL-D.

读取文件时不需要此 EOF 字符.这是因为一旦到达输入流的末尾,cin"就没有任何剩余(因为流现在已关闭),因此 while 循环退出.

This EOF character isn't needed when you are reading in a file. This is because once you hit the end of your input stream, there is nothing left to "cin"(because the stream is now closed), thus the while loop exits.

相关文章