检查输入是否为整数

时间:2014-04-07 15:21:55

标签: c fflush

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

我编写的这段代码非常适合整数和单个字符。但是如果我输入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;
}

3 个答案:

答案 0 :(得分:2)

在输入流上调用fflush会调用未定义的行为。即使您的实现为输入流定义它,它也不可移植。没有标准方法来刷新输入流。因此,fflush(stdin);不正确。您应该阅读这些字符并将其丢弃,直到stdin缓冲区中包含换行符。我建议您对功能进行以下更改。

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

另外,请阅读此C常见问题解答 - If fflush won't work, what can I use to flush input?

答案 1 :(得分:1)

fflush更改为fpurge会导致您的程序开始为我工作。

答案 2 :(得分:1)

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