C语言 将字符串转换为 32 位 int(有符号或无符号)并检查范围错误



我想将字符串(保证仅由数字组成(转换为 32 位整数。我知道strtolstrtoimax,但它们似乎返回 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()

我想转换一个字符串...
我知道strtolstrtoimax,但它们似乎返回 64 位 int。

有一些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?以获取更多想法。

最新更新