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

前端 未结 10 1412
情书的邮戳
情书的邮戳 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:55

    Hit Ctrl-Z (Ctrl-D on *nix systems) and hit enter. That sends an EOF and invalidates the stream.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 10:01
    int main() {
         string word;
         while (cin >> word) {
             // do something on the input word.
             if (foo)
               break;
         }
        // perform some other operations.
    }
    
    0 讨论(0)
  • 2020-11-29 10:06

    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.

    0 讨论(0)
  • 2020-11-29 10:08

    I guess you want to jump out at the end of file. You can get the value of basic_ios::eof , it returns true at the end of stream.

    0 讨论(0)
  • 2020-11-29 10:09

    You can make a check for a special word in input. F.e. "stop":

    int main( ){
       string word;
    
       while (cin >> word){
          if(word == "stop")
              break;
    
          //do sth on the input word
       }
    
    // perform some other operations
    }
    
    0 讨论(0)
提交回复
热议问题