for-loop and getchar() in C

你说的曾经没有我的故事 提交于 2019-12-04 07:11:14

问题


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 <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"); 
            }

        }

    }

If I input one operator,it loops two time. And the second time is the empty input.


回答1:


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);



回答2:


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();

    }

}


来源:https://stackoverflow.com/questions/34957825/for-loop-and-getchar-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!