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

时间:2017-07-31 08:46:31

标签: 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);

输出:821493369

gcc版本4.4.7 20120313(Red Hat 4.4.7-16) 你能告诉我这里做错了什么吗?感谢。

5 个答案:

答案 0 :(得分: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;
}

示例使用/输出

$ ./bin/strtoltst
987654321012345

您可以对转化执行其他错误检查,但至少要确保在致电errnostrtol后未设置strtoll

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

...
#include <stdint.h>
...
    int64_t num = 0;
    ...
    num = strtoll (str, NULL, 10);

结果是一样的。

答案 1 :(得分:3)

我可以重现并修复。

重现问题的代码

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

int main()
{
    char str[] = "987654321012345";
    long int num ;
    char *ix;
    num = 0;
    //num = atol(str);
    num = strtol(str, &ix, 10);
    printf("%ld\n", num);
    printf("%lu\n", sizeof(long));
    return 0;
}

符合预期:

821493369
8

编译警告后

  

警告:strtoll的隐式声明

原因:由于strtoll未声明,因此假定返回int,因此long值首先截断为int,然后再提升为long。

修复:只需取消注释#include <stdlib.h>行...

结论:警告不应被忽视!

答案 2 :(得分:2)

您应该使用long long作为号码的数据类型。

char str[] = "987654321012345";
long long num = strtoll(str, (char **)NULL, 10);
printf("%lld", num);

答案 3 :(得分:0)

根据C data type

  
      
  • 长签名整数类型。能够至少包含[-2,147,483,647,+ 2,147,483,647]范围;因此,它的大小至少为32位。
  •   
  • 长无符号整数类型。能够至少包含[0,4,294,967,295]范围;
  •   

还不够,所以您需要long longunsigned long long并使用%lli%llu

答案 4 :(得分:0)

“987654321012345”太大了。

  • Strol正在输出长型变量。
  • 长值为-2,147,483,648至2,147,483,647。

char str[] = "987654321012345";
char *pEnd;
long long num;
num = 0;
num = strtoull(str,&pEnd, 10);
printf("%lld", num);
return 0;
  • 长而不是长
  • strtoull而不是strtol

  • %lld而不是%ld