search

Home  >  Q&A  >  body text

c++ - window如何判断cin输入流的结束?

大家讲道理大家讲道理2806 days ago657

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 14:25:19

    1. When ctrl Z is in a line alone, or there is no character (including a space) in front of it, it indicates termination. In other cases, it will be recognized as a meaningless character. The definition under windows has nothing to do with the program.

    2.endl is the refresh stream. Since cin is a while loop that jumps out when an error occurs, there is no way to re-enter input without refreshing the status bits with cin.clear(). Your second program will output the original input letters, not because the data is still in the stream, but because after running the first while, the input data is saved in the global object p2. At the same time, because there is no reset state, the program directly The second while loop is skipped and the content of p2 is output directly

    Solution: Add cin.clear() and cin.sync() between the two while loops (if you don’t want to enter ctrl+z on a new line, you can also add cin.ignore())

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 14:25:19

    • linxu: Set Ctrl+D through EOF

    • windows can be set Ctrl+Z through EOF

    Add cin.clear()

    to the code
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main(){
        string p1, p2;
        
        cout << "first" << endl;
        while (cin >> p1){//
            p2 += p1;
        }
        cout << p2 << endl;
        
        cin.clear();//重新清空一下流的标志位,包括EOF
        
        cout << '\n' <<"second" <<endl;
        while (cin >> p1){
            p2 += p1;
        }
        cout << p2 << endl;
    
        return 0;
    }

    Input of EOF

    • In Linux, pressing Ctrl-D at the beginning of a new line means EOF (if you press Ctrl-D in the middle of a line, it means outputting the "standard input" buffer area, so this You must press Ctrl-D twice);

    • In Windows, Ctrl-Z means EOF. (By the way, pressing Ctrl-Z in Linux means interrupting the process and suspending it in the background. You can use the fg command to switch back to the foreground; pressing Ctrl-C means terminating the process.)

    So, what if you really want to type Ctrl-D? At this time, you must press Ctrl-V first, and then enter Ctrl-D. The system will not think this is an EOF signal. Ctrl-V means to interpret the next input "literally". If you want to enter Ctrl-V "literally", just enter it twice in a row.

    What is the EOF quoted from Teacher Ruan?

    reply
    0
  • Cancelreply