2016-04-02 57 views
1

我有一个while循环打印一个整数提示。我想错误检查用户何时输入字符,如'a'。但是,当我键入'a'时,它将永远打印“输入种子:种子必须是整数值,请再试一次”。虽然循环不等待scanf输入(“%d”)

int getSeed() { 
    int scanned, seed; 

    while (scanned == 0) { 
     printf("Enter the seed: "); 
     scanned = scanf("%d", &seed); 
     if (scanned == 0) { 
      printf("Seed must be an integer, try again\n"); 
     } 
    } 
    return seed; 
} 

我如何获得这个打印

Enter the seed: a Seed must be an integer, try again Enter the seed:

感谢。

编辑:解决了它,我添加了getchar();在scanf之后。

+2

[scanf not reading input]可能重复(http://stackoverflow.com/questions/5289542/scanf-not-reading-input) – FiReTiTi

+1

您的解决方案不会真正解决它。如果有人输入,事情仍然会出错,例如“aa”。如果你想读一行然后解析它,编写代码来做到这一点。 –

回答

0

scanf检查您的输入字符,发现它与转换说明符不匹配,因此它将其放回到输入流中。
然后在你的代码的while循环达到scanf一遍,上述过程再次发生(因为你已经写在输入流中a仍然存在)

因此,一个更好的解决办法是阅读它作为一个字符(或字符串),然后将其转换为整数。