scanf在while循环中 [英] scanf in while loop

查看:237
本文介绍了scanf在while循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中,scanf仅工作一次.我在做什么错了?

In this code, scanf works only once. What am I doing wrong?

#include <stdio.h>
#include <unistd.h>

int main()
{
    int i = 1;
    if (! fork())
    {
        while(i)
        {
            printf("Enter i");
            scanf("%d", &i);
            fflush(stdin);
            fflush(stdout);
        }
    }
    else
    {
        printf("Parent\n");
    }
    return(0);
}

推荐答案

已经建议您

It has already been recommended that you not use scanf. If you feel you must use scanf, you really should be checking the return value to determine if an input error occurred prior to the conversion.

还应注意,您不应通过fflush刷新stdin,因为它会调用未定义的行为.如果您认为必须刷新stdin,则可能要参考

It has also been noted that you should not be flushing stdin via fflush as it invokes undefined behavior. If you feel that you must flush stdin, you may want to refer to the answers to this question.

如果输入了无效值,例如"1,234" ,则scanf将接受'1',234/n" 将保留在输入流中.由于不能保证fflush(stdin)正常工作,因此对scanf的后续调用将一遍又一遍地拒绝相同的',',因此永远不会取得任何进展.如果检查返回值是否为零(表示早期匹配失败),则可以避免此无限循环.在再次调用scanf之前,还必须从输入流中删除无效字符.

If an invalid value such as "1,234" is entered, scanf will accept the '1' and the ",234/n" will be left in the input stream. Since fflush(stdin) is not guaranteed to work, subsequent calls to scanf will keep rejecting the same ',' over and over again, never making any progress. If the return value is checked for zero (indicating an early matching failure), this infinite loop can be avoided. It is also necessary to remove the invalid character(s) from the input stream prior to another call to scanf.

也请参见 引起无限循环的scanf() .

See scanf() causing infinite loop as well.

这篇关于scanf在while循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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