gpt4 book ai didi

c++ - 将整数数组转换为数字

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:34 24 4
gpt4 key购买 nike

想想我有一个像这样的整数数组:

a[0]=60; a[1]=321; a[2]=5;

现在我想把这个数组全部转换成一个整数,比如运行代码后int b变成603215。

怎么做?

最佳答案

使用std::stringstream:

#include <iostream>
#include <sstream>

int main() {
std::stringstream ss;
int arr[] = {60, 321, 5};

for (unsigned i = 0; i < sizeof arr / sizeof arr [0]; ++i)
ss << arr [i];

int result;
ss >> result;
std::cout << result; //603215
}

请注意,在 C++11 中,这个有点难看的循环可以替换为:

for (int i : arr)
ss << i;

此外,考虑到溢出的可能性很大,可以使用 ss.str() 访问数字的字符串形式。为了避免溢出,使用它可能比试图将它塞进一个整数更容易。也应考虑负值,因为这仅在第一个值为负时才有效(并且有意义)。

关于c++ - 将整数数组转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11201015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com