字符串很长,没有给我正确的答案

For*_*ner 2 c linux string long-integer

我试图将存储在c字符串中的数字转换为long int.但我没有得到预期的输出:

char str[] = "987654321012345";
long int num ;
num = 0;
//num = atol(str);
num = strtol(str, (char **) NULL, 10);
printf("%ld", num);
Run Code Online (Sandbox Code Playgroud)

输出: 821493369

gcc版本4.4.7 20120313(红帽4.4.7-16)你能告诉我这里做错了什么吗?谢谢.

Dav*_*ica 5

除了使用之外long long,您还可以使用精确的宽度类型stdint.h.例如,要保证和64位有符号数,您可以使用该int64_t类型.无论您做什么,都不要强制 NULL转换char **并始终验证您的转化.例如,

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main (void) {

    char str[] = "987654321012345";
    long num = 0;
    errno = 0;

    num = strtol (str, NULL, 10);
    if (errno) {    /* validate strtol conversion */
        perror ("strtol conversion failed.");
        return 1;
    }

    printf ("%ld\n", num);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

示例使用/输出

$ ./bin/strtoltst
987654321012345
Run Code Online (Sandbox Code Playgroud)

您可以对转换执行其他错误检查,但至少请确保errno在调用strtol或之后未设置strtoll.

如果您想使用保证宽度类型,则可以进行以下更改:

...
#include <stdint.h>
...
    int64_t num = 0;
    ...
    num = strtoll (str, NULL, 10);
Run Code Online (Sandbox Code Playgroud)

结果是一样的.