#include <stdio.h>
int main(int argc, char** argv) {
int num = 0;
printf("Input: ");
scanf("%d", &num); <<<
printf("%d\n", num);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
scanf("%d", #);
Clang-Tidy: 'scanf' 用于将字符串转换为整数值,但函数不会报告转换错误;考虑使用“strtol”代替
我用 CLion 编写了一个非常简单的代码,它推荐我使用“strtol”而不是“scanf”。
但我只使用整数变量,没有字符串。我不明白为什么弹出检查消息。
如何修改此代码?
如何修改此代码?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
enum { INPUT_SIZE = 30 };
int main () {
char *ptr;
long ret;
char str[INPUT_SIZE];
fgets(str, INPUT_SIZE, stdin);
ret = strtol(str, &ptr, 10);
if( ret == LONG_MAX || ret == LONG_MIN ) {
perror("!! Problem is -> ");
}
else if (ret) {
printf("The number is %ld\n", ret);
}
else {
printf("No number found input is -> %s\n", ptr);
}
return(0);
}
Run Code Online (Sandbox Code Playgroud)
如果成功,则
strtol()返回转换后的 long int 值。如果不成功,则在无法执行转换时
strtol()返回0。如果正确值超出可表示值的范围,则根据值的符号strtol()返回LONG_MAX或LONG_MIN。如果不支持 base 的值,则strtol()返回0。如果不成功,
strtol()则将 errno 设置为以下值之一:错误代码:
EINVAL不支持 base 的值。
ERANGE转换导致溢出。来源:IBM
您可以使用scanf()例如检查溢出吗?
Input: 1234 stackoverflow
Output: The number is 1234
Input: 123nowhitespace
Output: The number is 123
Input: number is 123
Output: No number found input is -> number is 123
Input: between123between
Output: No number found input is -> between23between
Input: 9999999999999999999
Output: !! Problem is -> : Result too large
Run Code Online (Sandbox Code Playgroud)
也许离题了,但是Jonathan Leffler在他的评论(在另一个主题中)中说,将警告作为错误处理。