c - 将字符串转换为 32 位 int(有符号或无符号)并检查范围错误
问题描述
我想将一个字符串(保证只包含数字)转换为 32 位整数。我知道strtol
and strtoimax
,但这些似乎返回 64 位整数。
这就是我目前的做法:
#include <errno.h>
#include <inttypes.h>
typedef int32_t Int32;
Int32 strToIntValue(char* str) {
char* end;
errno = 0;
int ret = strtoimax(str, &end, 10);
if (errno==ERANGE) {
printf("range error!\n");
return 0;
}
else {
return (Int32)ret;
}
}
解决方案
标准 C 库没有strtoint32()
.
我想将字符串 ... 转换为 32 位 int。
我知道strtol
andstrtoimax
,但这些似乎返回 64 位整数。
肯定有long strtol()
满足OP的需求。它形成一个至少32 位的整数。如果需要,请使用它和其他测试。
#include <ctype.h>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
// really no need for this:
// typedef int32_t Int32;
// Int32 strToIntValue(char* str) {
int32_t strToIntValue(const char* str) {
char* end;
errno = 0;
long num = strtol(str, &end, 10);
if (num == end) {
printf("No conversion error!\n");
return 0;
}
#if LONG_MAX > INT32_MAX
if (num > INT32_MAX) {
num = INT32_MAX;
errno = ERANGE;
}
#endif
#if LONG_MIN < INT32_MIN
if (num < INT32_MIN) {
num = INT32_MIN;
errno = ERANGE;
}
#endif
if (errno==ERANGE) {
printf("range error!\n");
return 0;
}
// Maybe check for trailing non-white space?
while (isspace((unsigned char) *end) {
end++;
}
if (*end) {
printf("Trailing junk!\n");
return 0;
}
// else {
return (int32_t) num;
//}
}
考虑将错误输出打印到stderr
而不是stdout
.
// printf("range error!\n");
fprintf(stderr, "range error!\n");
请参阅为什么 stdlib.h 中没有 strtoi?更多想法。
推荐阅读
- android - Android Studio“忘记”布局文件存在
- http - 使用 Http 获取请求,使用 WebSocket 给出结果
- java - 使用 Java 开发工具包在代码中嵌入 AWS IAM 凭证
- r - R - 从 json 中提取数据
- python - json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 运行代码时出现此错误
- react-native - react-native 捆绑图像路径
- c++ - 以优雅的方式在游戏引擎中管理指向已销毁对象的指针
- amazon-web-services - AWS S3 存储的对象锁定设置不起作用
- asp.net-core - 自定义错误页面 .Net Core Web 应用程序未显示 500 错误
- docker - 在 windows 容器中托管后无法通过浏览器浏览 Asp.net core web api