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

问题描述 投票:1回答:1

我想将一个字符串(保证只包含数字)转换为32位int。我知道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 string string-conversion int32
1个回答
0
投票

标准C库没有strtoint32()

我想将字符串...转换为32位int。我知道strtolstrtoimax,但它们似乎返回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");

请参阅Why is there no strtoi in stdlib.h?了解更多想法。

© www.soinside.com 2019 - 2024. All rights reserved.