for-loop and getchar() in C

后端 未结 2 1977
别那么骄傲
别那么骄傲 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);
    
    0 讨论(0)
  • 2021-01-29 14:55

    If you don't want to change a lot in your code, I suggest just insert another getchar at the end of for loop to consume '\n':

    #include <stdio.h>
    #pragma warning(disable : 4996) 
    
    void main() {
    
        int f, a = 10, b = 20;
        for (int i = 0; i < 5; i++)
        {
            char ch;
            ch = getchar();
            printf("ch = %c\n", ch);
            switch (ch)
            {
                case '+': f = a + b; printf("f = %d\n", f); break;
                case '−': f = a - b; printf("f = %d\n", f); break;
                case '*': f = a * b; printf("f = %d\n", f); break;
                case '/': f = a / b; printf("f = %d\n", f); break;
                default: printf("invalid operator\n"); 
            }
            getchar();
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题