c++ when will while(cin>>s) stop

后端 未结 2 345
悲&欢浪女
悲&欢浪女 2021-01-15 05:30

I\'m new to C++. I\'m sorry if this question is duplicated but I just can\'t find similar question.

very basic code:

string s;
while (cin >> s)         


        
相关标签:
2条回答
  • 2021-01-15 05:57

    while (cin >> s) { ... } will loop as long as the input is valid. It will exit the loop when the attempted input fails.

    There are two possible reasons for failure:

    1. Invalid input
    2. End of file

    Assuming that the input itself is valid, in order to terminate the loop the input stream has to reach the end.

    When the input is actually a file, recognizing the end is easy: when it runs out of characters it's at the end of the file. When it's the console, it's not so easy: you have to do something artificial to indicate the end of the input.

    Do that, you have to tell the terminal application (which controls the console) that there is no more input, and the terminal application, in turn, will tell your program that it's at the end of the input.

    The way you do that depends on the terminal application, which is typically part of the operating system.

    • On Windows, ctrl-Z tells the terminal application that you're at the end of your input.
    • On Unix systems, it's ctrl-D.
    0 讨论(0)
  • 2021-01-15 06:12

    You can signal EOF via CTRL-D or CTRL-Z.

    Or, you can check for a particular string to break the loop, like below:

    string s;
    while (cin >> s)
      {
         if(s == "end")
              break;
         cout << s << endl;
      }
    
    0 讨论(0)
提交回复
热议问题