c - 你如何在 C 中使用 scanf 识别输入不是数字?
问题描述
当例如“a”是输入值时,我如何生成错误消息?
#include <stdio.h>
int main ( void )
{
int a;
scanf ("%d" , & a) ;
// if a is not a number, then generate error
return 0 ;
}
解决方案
您要确保scanf
实际正确识别了一个整数,因此请检查返回值。函数族scanf
返回一个整数,表示正确解析的元素的数量,所以如果你这样做,scanf("%d", ...)
你应该期望1
在有效整数的情况下返回值:
int a;
if (scanf("%d", &a) != 1) {
// the value read was not an integer, the end of file was reached, or some other error occurred
} else {
// good
}
这就是你可以做的所有事情scanf
,但是请注意,遗憾的是,这不足以确保扫描的值确实是用户输入的实际值,并且它没有溢出。
在 C 中可以做到这一点的唯一合理方法是首先将输入作为字符串获取,然后使用strtol
能够正确报告解析和溢出错误的函数或类似函数对其进行解析。