[英]Convert string to 32-bit int (signed or unsigned) and check for range errors
我想將字符串(保證僅由數字組成)轉換為 32 位整數。 我知道strtol
和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 位整數。
我知道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;
//}
}
考慮將錯誤輸出打印到stderr
而不是stdout
。
// printf("range error!\n");
fprintf(stderr, "range error!\n");
請參閱為什么 stdlib.h 中沒有 strtoi? 更多想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.