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

前端 未结 10 1461
情书的邮戳
情书的邮戳 2020-11-29 09:12

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

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


        
10条回答
  •  时光说笑
    2020-11-29 09:58

    cin >> some_variable_or_manipulator will always evaluate to a reference to cin. If you want to check and see if there is more input still to read, you need to do something like this:

    int main( ){
         string word;
         while (cin.good()){
             cin >> word;
             //do sth on the input word
         }
    
        // perform some other operations
    }
    

    This checks the stream's goodbit, which is set to true when none of eofbit, failbit, or badbit are set. If there is an error reading, or the stream received an EOF character (from reaching the end of a file or from the user at the keyboard pressing CTRL+D), cin.good() will return false, and break you out of the loop.

提交回复
热议问题