简体   繁体   English

将整数数组转换为数字

[英]Converting an Integer Array into a Number

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 b become 603215 after running the code. 现在,我想将整个数组转换为整数,例如运行代码后int b变为603215。

How to do it? 怎么做?

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() . 同样,看到溢出的可能性很大,可以使用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. 负值也应考虑在内,因为只有在第一个值为负数时,这才起作用(并有意义)。

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

Concat all the numbers as a string and then convert that to number 将所有数字连接为字符串,然后将其转换为数字

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

This algorithm will work: 该算法将起作用:

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

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);

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

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