c 编程中 fflush(stdin) 有什么用? [英] What is the use of fflush(stdin) in c programming?

查看:26
本文介绍了c 编程中 fflush(stdin) 有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have the following program

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char ans[8];
    int i;
    for(i=1;i<=3;i++)
    {
        printf("
 What is the unit of traffic ?");
        scanf("%s",ans);
        fflush(stdin);

        if(stricmp(ans,"Earlang")==0)
        {
            printf("
Answer is correct");
            exit(1);
        }
        else
            if(i<3)
            printf("
 Try Again!
");
    }
    printf("
 Nunit of traffic is Earlang:");
}

What is the use of fflush(stdin) in this program?

解决方案

It's not in standard C, so the behavior is undefined.

Some implementation uses it to clear stdin buffer.

From C11 7.21.5.2 The fflush function, fflush works only with output/update stream, not input stream.

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

这篇关于c 编程中 fflush(stdin) 有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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