首页 > 解决方案 > 将字符串转换为 32 位 int(有符号或无符号)并检查范围错误

问题描述

我想将一个字符串(保证只包含数字)转换为 32 位整数。我知道strtoland 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;
    }
}

标签: cstringstring-conversionint32

解决方案


标准 C 库没有strtoint32().

我想将字符串 ... 转换为 32 位 int。
我知道strtoland 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?更多想法。


推荐阅读