C 将字符串转换为32位整数(有符号或无符号),并检查范围错误
我想将字符串(保证仅由数字组成)转换为32位整数。我知道C 将字符串转换为32位整数(有符号或无符号),并检查范围错误,c,string,string-conversion,int32,C,String,String Conversion,Int32,我想将字符串(保证仅由数字组成)转换为32位整数。我知道strtol和strtoimax,但它们似乎返回64位整数 我现在就是这样做的: #包括 #包括 typedef int32_t int32; Int32 strToIntValue(字符*str){ 字符*结束; errno=0; int-ret=strtoimax(str和end,10); if(errno==ERANGE){ printf(“范围错误!\n”); 返回0; } 否则{ 返回(Int32)ret; } } 标准C库没有s
strtol
和strtoimax
,但它们似乎返回64位整数
我现在就是这样做的:
#包括
#包括
typedef int32_t int32;
Int32 strToIntValue(字符*str){
字符*结束;
errno=0;
int-ret=strtoimax(str和end,10);
if(errno==ERANGE){
printf(“范围错误!\n”);
返回0;
}
否则{
返回(Int32)ret;
}
}
标准C库没有stroint32()
我想转换一个字符串。。。到32位整数。我知道
strtol
和strtoimax
,但它们似乎返回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;
//}
}
有关更多想法,请参阅。标准C库没有
strotInt32()
我想转换一个字符串。。。到32位整数。我知道
strtol
和strtoimax
,但它们似乎返回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;
//}
}
查看以获取更多想法。如果(ret
INT32_MIN
和INT32_MAX
,如果您有
)如果您确定字符串只有数字,则不需要进行错误检查,您可以使用atoi
@JimDanner,但如果数字超出范围,则atoi
将做什么?re“typedef int32\u t int32;
”,为什么要添加这种级别的混淆?@AdrianMole显然在这种情况下,行为是未定义的,您可以添加如下内容:如果(retINT_MAX){…错误代码
?(或者更具体地说,INT32_MIN
和INT32_MAX
,如果您有
)如果您确定字符串只有数字,那么错误检查就不是必需的,您可以使用atoi
@JimDanner,但是如果数字超出范围,atoi
会做什么?re“typedef int32\u t int32;
”,为什么要添加这种级别的混淆??@AdrianMole显然在这种情况下,行为是未定义的,