Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

file-io

eof

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

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.

like image 925
user630983 Avatar asked Mar 19 '11 04:03

user630983


People also ask

How do you stop a CIN while looping?

On Unix systems, it's ctrl-D .

Can you put CIN in a while loop?

Well, you use cin inside a while loop when you need the user to enter a value that will be used after that, in the same loop. Everytime the loop runs, the user can chose something else. For example, calculating x*y.

Can CIN be used for strings?

Inputting a stringYou can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.

Does CIN wait for input?

The program works as it should whenever you enter an Int, but for the case you enter an invalid datatype I want it to ask for input again.


1 Answers

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.

like image 134
Mike Lewis Avatar answered Sep 19 '22 08:09

Mike Lewis