for-loop and getchar() in C

后端 未结 2 1978
别那么骄傲
别那么骄傲 2021-01-29 14:19

Why does the code get the empty data directly in even times? I have no idea what is going on. Thank you very much.

    #include 
    #pragma warnin         


        
2条回答
  •  离开以前
    2021-01-29 14:49

    Let's say you typed a followed by Enter.

    The first call to getchar() returns a but the newline is still left in the input stream. The next call to getchar() returns the newline without waiting for your input.

    There are many ways to take care of this problem. One of the simplest ways is to ignore the rest of the line after the call to getchar().

    ch = getchar();
    
    // Ignore the rest of the line.
    int ignoreChar;
    while ( (ignoreChar = getchar()) != '\n' && ignoreChar != EOF );
    

    You can wrap that in a function.

    void ignoreLine(FILE* in)
    {
       int ch;
       while ( (ch = fgetc(in)) != '\n' && ch != EOF );
    }
    

    and use

    ch = getchar();
    
    // Ignore the rest of the line.
    ignoreLine(stdin);
    

提交回复
热议问题