简体   繁体   English

使用atoi将字符数组转换为int可以得到不同的值

[英]Converting character array to int with atoi gives a different value

Trying to convert a character array to int data type in C++11. 尝试在C ++ 11中将字符数组转换为int数据类型。 Why is the int value i different than the character array value ? 为什么inti与字符数组value Is this because 51,093,843,802 is greater than 2,147,483,647 ? 这是因为51,093,843,802大于2,147,483,647吗?

// Example program
#include <iostream>
#include <string>

int main()
{
    char value[] = "51093843802";
    printf("%s\n", value);
    int i = std::atoi(value);
    printf("%d\n", i);
}

Output: 输出:

51093843802
-445763750

As you said, the value 51093843802 can't (usually) fit in int , and overflowing a signed integer is undefined behavior (and thus a huge no no) in C++. 如您所说,值51093843802不能(通常)适合int ,并且溢出有符号整数是C ++中的未定义行为 (因此,是一个很大的“不”)。

You need to use long long int (or just long int will do if you're on a system where that's 64 bits ): 您需要使用long long int (或者,如果您使用的是64位的系统,则只需使用long int ):

#include <iostream>
#include <string>

int main()
{
    char value[] = "51093843802";
    std::cout << value << '\n';
    long long i = std::stoll(value);
    std::cout << i << '\n';
}

Output: 输出:

 51093843802 51093843802 

Notice that I changed i 's datatype to be long long , std::atoi to std::stoll and printf to std::cout , to be more in line with C++ best practises. 注意,我将i的数据类型更改为long long ,将std::atoi更改为std::stoll ,将printf更改为std::cout ,以更符合C ++的最佳实践。

int is too small to store 51093843802 ( range of values ). int太小,无法存储51093843802值的范围 )。 Use atoll (to long long) and replace i's type to int64_t : 使用atoll (很长很长)并将我的类型替换为int64_t

char value[] = "51093843802";
printf("%s\n", value);
int64_t i = std::atoll(value);
printf("%ld\n", i);

Using long with atol is not safe because on Windows long size is 4 bytes even on 64bits system. atol一起使用long是不安全的,因为即使在64位系统上,Windows上的long大小也为4字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM