C: 如果用户使用 fflush(stdin) 输入字符,程序不会再次询问用户

标签 c scanf fflush

显然我不会在这里发布我的整个代码,因为它很长,毕竟它是一个税收计算器。这个问题适用于我所有需要 double 值作为用户输入的 scanfs。基本上正如标题所说,我的程序不会要求用户输入另一个值,即使它是一个字符,这显然不是 double 值,所以一些帮助将不胜感激。请原谅我,因为我还在第一年的类(class)中,对编程还不是很了解。

double salary;
printf("This program will compute your yearly and monthly witholding tax for you \n");
printf("How much is your total monthly salary? ");
fflush(stdin);
scanf("%lf", &salary);
while (salary < 0)
{
    printf("\n");
    printf("Invalid Input\n");
    printf("How much is your total monthly salary? ");
    fflush(stdin);
    scanf("%lf", &salary);
}

最佳答案

您正确地诊断了问题:无效输入保留在输入缓冲区中,导致随后的每个 scanf失败。您无法使用 fflush 更正此问题,因为它没有为输入流定义。请注意,您还滥用了 scanf因为您没有测试返回值。

您的问题的简单通用解决方案是:替换对 scanf 的调用调用一个函数,该函数从用户那里读取一行并将其重复解析为字符串,直到输入 EOF 或正确的输入。

此函数采用范围进行有效性检查。如果您不想接受所有输入,可以传递无穷大。

int getvalue(const char *prompt, double *vp, double low, double high) {
    char buffer[128];
    for (;;) {
        printf("%s ", prompt);
        if (!fgets(buffer, sizeof buffer, stdin)) {
            printf("EOF reached, aborting\n");
            // you can also return -1 and have the caller take appropriate action
            exit(1);
        }
        if (sscanf(buffer, "%lf", vp) == 1 && *vp >= low && *vp <= high)
            return 0;
        printf("invalid input\n");
    }
}

在您的代码片段中,您将用以下内容替换所有内容:

double salary;
printf("This program will compute your yearly and monthly withholding tax for you\n");
getvalue("How much is your total monthly salary?", &salary, 0.0, HUGE_VAL);

HUGE_VAL<math.h> 中定义, 但它的值(value)对于薪水来说似乎有点高,你可以写一个像样的最大值,比如 1E9 .

关于C: 如果用户使用 fflush(stdin) 输入字符,程序不会再次询问用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33846065/

相关文章:

c - 在C中读取单个字符

c - 如何使用分隔符使用 fscanf 扫描文本文件?

c - fflush() 始终返回 0 但将 errno 设置为 11(资源暂时不可用)

c - 如何使用 "foreign function interface"从 Go 调用 C

c - 抛出未处理的异常 : write access violation

c - 打印 scanf 输入,可能来自被忽略的非字母之间

c# - C# 中是否有类似于 C 中的 fflush() 的东西?

c - fwrite() 和文件损坏

c - 使用 scanf() 的段错误

c - 为什么 Windows 上的 gcc 将特定值分配给变量?