2

我需要创建一个从用户那里获取输入的函数,并确保它是一个整数并且不包含任何字符。

我编写了这段代码,它非常适用于整数和单个字符。但如果我输入dfd即多字符输入,它就会终止。下面是我在 Linux 上用 gcc 编译的代码:

#include <ctype.h>

int getint()
{
    int input = 0;
    int a;
    int b, i = 0;
    while((a = getchar()) != '\n')
    {
        if (a<'0'||a>'9')
        {
            printf("\nError in input!Please try entering a whole number again:");
            input=0;
            fflush(stdin);
            return getint();
        }
        b = a - '0';
        input = ((input*10) + b);
        i++;
    }
    return input;
}
4

3 回答 3

2

Calling fflush on an input stream invokes undefined behaviour. Even if your implementation defines it for input streams, it's not portable. There is no standard way to flush an input stream. Therefore, the fflush(stdin); is not correct. You should read the characters and discard them till and including the newline in the stdin buffer. I suggest the following change to your function.

int getint(void) {
    int input = 0;
    int a;

    while((a = getchar()) != '\n') {
        if (a < '0' || a > '9') {
            printf("Error in input!Please try entering a whole number again:\n");
            input = 0;

            // read and discard characters in the stdin buffer up till
            // and including the newline
            while((a = getchar()) != '\n'); // the null statement
            return getint();  // recursive call
        }
        input = (input * 10) + (a - '0');
    }
    return input;
}

Also, please read this C FAQ - If fflush won't work, what can I use to flush input?

于 2014-04-07T16:05:30.060 回答
1

更改fflushfpurge导致您的程序开始为我工作。

于 2014-04-07T15:34:15.920 回答
1

问题可能是调用 fflush(stdin) 是未定义的。fflush 用于刷新输出流,而不是输入流。尝试用另一种方法替换它以清除剩余的输入缓冲区,while (getchar() != '\n');看看是否能解决问题。(你可能应该做一些更强大的事情,比如捕捉 EOF,这样你就不会陷入无限循环)

于 2014-04-07T15:35:46.193 回答