输入错误类型后如何“复活”stdin

时间:2013-12-28 16:54:34

标签: c exception stdin

如果用户只输入整数,则下面的代码就像预期的那样。

#include <stdio.h>

int main()
{
    int input1, input2;
    int error;

    error = scanf("%d", &input1);
    if( !error)
        printf("Error: Your input was wrong\n");
    else
        printf("Your input was: %d\n", input1);

    error = scanf("%d", &input2);
    if( !error)
        printf("Error: Your input was wrong");
    else
        printf("Your input was: %d\n", input2);

}

但是,如果用户在第一个提示符下键入abcd,程序将打印出来:

Error: Your input was wrong
Error: Your input was wrong

跳过第二个scanf()
一旦输入失败,我怎样才能“复活”stdin,以便可以重复使用它?

1 个答案:

答案 0 :(得分:3)

if(!error){
    printf("Error: Your input was wrong\n");
    scanf("%*[^\n]");
} else
    printf("Your input was: %d\n", input1);