for循环和C语言中的getchar() [英] for-loop and getchar() in C

查看:368
本文介绍了for循环和C语言中的getchar()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么代码偶数次直接获取空数据?我不知道发生了什么事. 非常感谢.

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.

推荐答案

假设您键入a,然后键入 Enter .

Let's say you typed a followed by Enter.

第一次调用getchar()返回a,但是换行符仍留在输入流中.下次调用getchar()时,无需等待您的输入即可返回换行符.

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.

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

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

并使用

ch = getchar();

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

这篇关于for循环和C语言中的getchar()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆