请求int输入,如何防范char?

时间:2013-11-03 00:55:29

标签: c input char int scanf

我要求int输入,然后检查它是否等于正确的答案,但我如何防止用户输入字符?

    int main()
    {
       int response;
       int answer;

       scanf("%f", &response);
       if(response == answer)
       {
         //Correct! 
       }
       else
       {
         //Incorrect!
       }
    }

2 个答案:

答案 0 :(得分:3)

scanf(3)给出了您应该使用的结果(成功读取项目的数量)。并且您的%f不正确,因此您应该编码

if (scanf(" %d", &response)==1) { 
  /// did got some response
}

我考虑了comment中的Jonathan Leffler的好answer of Soumya Koumar ...

答案 1 :(得分:3)

您必须使用%d从输入中扫描 int

根据scanf定义,它返回成功时扫描的项目数,或者如果匹配失败则返回0。因此,如果您在标准输入中输入 char 而不是 integer ,它将返回0作为返回值。

您可以执行以下操作:

if (scanf(....) == 0) { 
    /* error */ 
} else {
    /* do my work */
}