How to signify no more input for string ss in the loop while (cin >> ss)

user630983 picture user630983 · Mar 19, 2011 · Viewed 47.1k times · Source

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

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.

Answer

Mike Lewis picture Mike Lewis · Mar 19, 2011

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

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.