0

显然我不会在这里发布我的整个代码,因为它很长,毕竟它是一个税收计算器。这个问题适用于我所有需要双值作为用户输入的 scanfs。基本上正如标题所说,我的程序不会要求用户输入另一个值,即使它是一个字符,这显然不是一个 double 值,所以非常感谢一些帮助。请原谅我,因为我仍处于课程的第一年并且对编程一无所知。

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

1 回答 1

3

您正确诊断了问题:无效输入保留在输入缓冲区中,导致每个后续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>,但无论如何它的薪水价值似乎有点高,您可以写一个像样的最大值,例如1E9.

于 2015-11-21T17:45:40.457 回答