C++ 将整数数组转换为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11201015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:55:53  来源:igfitidea点击:

Converting an Integer Array into a Number

c++arraysinteger

提问by Inside Man

Think I have an integer array like this:

认为我有一个这样的整数数组:

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

now I want to convert the whole of this array into an integer number, for example int bbecome 603215 after running the code.

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

How to do it?

怎么做?

回答by chris

Use a std::stringstream:

使用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
}

Note that in C++11 that mildly ugly loop can be replaced with this:

请注意,在 C++11 中,稍微难看的循环可以替换为:

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

Also, seeing as how there is a good possibility of overflow, the string form of the number can be accessed with ss.str(). To get around overflow, it might be easier working with that than trying to cram it into an integer. Negative values should be taken into consideration, too, as this will only work (and make sense) if the first value is negative.

此外,鉴于溢出的可能性很大,可以使用ss.str(). 为了避免溢出,使用它可能比尝试将其塞入整数更容易。负值也应该考虑在内,因为这只有在第一个值为负时才有效(并且有意义)。

回答by Kalai Selvan Ravi

int a[] = {60, 321, 5};

int finalNumber = 0;
for (int i = 0; i < a.length; i++) {
    int num = a[i];
    if (num != 0) {
        while (num > 0) {
            finalNumber *= 10;
            num /= 10;
        }
        finalNumber += a[i];
    } else {
        finalNumber *= 10;
    }
}

finalNumber has a result: 603215

finalNumber 有结果:603215

回答by Karesh A

Concat all the numbers as a string and then convert that to number

将所有数字连接为字符串,然后将其转换为数字

#include <string>
int b = std::stoi("603215");

回答by NIlesh Sharma

This algorithm will work:

该算法将起作用:

  1. Convert all the integer values of array into string using for loop.
  2. Append all the string values now to one string from index 0 to length of array.
  3. Change that string into an integer again.
  1. 使用 for 循环将数组的所有整数值转换为字符串。
  2. 现在将所有字符串值附加到从索引 0 到数组长度的一个字符串中。
  3. 再次将该字符串更改为整数。

回答by Kaje

Iterate the array and convert the values into string. Then concatenate all of them and convert back to integer.

迭代数组并将值转换为字符串。然后连接所有它们并转换回整数。

#include <string>

int a[] = {60, 321, 5};
std::string num = "";
for(auto val : a)
    num += a;
int b = std::stoi(num);