为什么我应该在这个程序中使用 fflush(stdin) ? [英] Why should I use fflush(stdin) in this program?

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

问题描述

我知道它用于清理键盘缓冲区,但我不明白何时/为什么需要使用它,或者我是否真的需要使用它.

I know that it is use to clean the keyboard buffer, but I don't understand when/why I need to use it or if I really need to.

例如,在我为班级编写的这段代码中,只有在 while 之后将 fflush(stdin) 放入 main 函数中,它才有效,并且我之所以知道这一点,是因为教授告诉我在我向他展示错误后才这样做.

For example, into this code that I made for my class, it only works if I put fflush(stdin) into the main function right after the while, and I only know this because the professor told me to do so after I had showed him the erro.

问题是否与struct有关,这就是为什么我应该使用 fflush(stdin)?

Does the problem have something related with the struct and thats why I should use fflush(stdin)?

代码如下:

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

struct CLIENTES
{
    int ano_nasc, cpf[11];
    float renda_m;
    char nome[50];
}; //Lista de Objetos

int main(void) 
{
    //Declaracao de Variaveis
    int cont=0, num, num_2, client, i, j;
    CLIENTES *vet;

    //Leitura de Dados
    printf("Digite o numero de Clientes: ");
    scanf("%d%*c", &num);
    vet = (CLIENTES*)malloc(num*sizeof(*vet));
    printf("Digite os Dados do Cliente.");

    while (cont != num)
    {  
        fflush(stdin);
        printf("\nNome: ");
        fgets(vet[cont].nome, sizeof(vet[cont].nome), stdin);
        printf("\nAno de Nascimento: ");
        scanf("%d", &vet[cont].ano_nasc);
        printf("\nCPF: ");
        scanf("%d", &vet[cont].cpf);
        printf("\nRenda Mensal: ");
        scanf("%f", &vet[cont].renda_m);
        cont++;
    }

    printf("\nDigite o numero do cliente que voce deseja conferir: ");
    scanf("%d", &num_2);
    for (i=0;i<num;i++)
    {
        if(num_2 == num)
        {
            printf("\nO que deseja saber sobre ele?\n");
            printf("1-Nome\n2-Ano de Nascimento\n3-CPF\n4-Renda Mensal\n\n\n");
            scanf("%d", &client);
            if (client == 1)
            {
                printf("Nome: %s", vet[(num_2)-1].nome );
            }
            else if(client == 2)
            {
                printf("Ano de Nascimento: %d", vet[num_2].ano_nasc );
            }
            else if(client == 3)
            {
                for(j=0;j<11;j++)
                {
                    printf("CPF: %d", vet[num_2].cpf[j]);
                }
            }
            else if(client == 4)
            {
                printf("Renda Mensal: %f", vet[num_2].renda_m );
            } 
        }
    }

    //Finalizando o Programa
    printf("\n\nFim do Programa!");
    getch();
    return 0;
} 

推荐答案

其实教授说standard C是错的.按照标准,调用fflush输入流(例如 stdin)是未定义的行为.

Actually the professor is wrong if speaking of standard C. According to the standard, calling fflush on an input stream (such as stdin) is undefined behaviour.

然而,在许多实现中(包括 Linux†、OS X、各种 BSD 等)fflush(stdin) 会丢弃任何已缓冲但尚未消耗的输入.这个非标准特性用于在你的程序中清除前一个 scanf 在输入缓冲区中留下的尾随换行符.

However, in many implementations (including Linux†, OS X, various BSDs, etc.) fflush(stdin) discards any input that has been buffered but not yet consumed. This non-standard feature is used in your program to clear the trailing newline left in the input buffer by the previous scanf.

man fflush 在 Linux 上很友好地提到这是非标准的(尽管措辞并不完全暗示未定义的行为):

man fflush on Linux is kind enough to mention that this is non-standard (although the wording doesn't quite suggest undefined behaviour):

标准没有规定输入流的行为.

The standards do not specify the behavior for input streams.

同时7.21.5.2下的C11标准fflush函数说:

Meanwhile the C11 standard under 7.21.5.2 The fflush function says:

如果 stream 指向一个输出流或更新流,其中最近的操作没有输入,fflush 函数会导致该流的任何未写入数据传送到主机环境以写入文件;否则,行为未定义.

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.

† 根据评论,尽管 man fflush 声称它应该在 Linux 上运行,但这种非标准行为可能无法在 Linux 上运行.

† According to comments this non-standard behaviour may not work on Linux despite man fflush claiming that it should.

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

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