C中的for循环和getchar()

时间:2016-01-22 23:45:50

标签: c for-loop getchar

为什么代码会在偶数时间直接获取空数据?我不知道发生了什么事。 非常感谢你。

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

        }

    }

enter image description here

如果我输入一个运算符,它会循环两次。第二次是空输入。

2 个答案:

答案 0 :(得分:3)

我们假设您输入了a,然后输入 Enter

第一次调用getchar()会返回a,但换行符仍保留在输入流中。下一次调用getchar()会返回换行符,而不会等待您的输入。

有很多方法可以解决这个问题。最简单的方法之一是在调用getchar()之后忽略其余部分。

ch = getchar();

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

你可以将它包装在一个函数中。

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

并使用

ch = getchar();

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

答案 1 :(得分:0)

如果您不想在代码中进行大量更改,我建议您在for循环结束时插入另一个getchar以使用'\ 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();

    }

}