转换一个整数数组成数 [英] Converting an Integer Array into a Number

查看:145
本文介绍了转换一个整数数组成数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我有一个整数数组像这样: A [0] = 60;一个[1] = 321; A [2] = 5; 现在我想整个这个数组转换为整数,例如 INT b 运行后变成603215在code。怎么办呢?

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. How to do it?

推荐答案

使用的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婉转丑陋的循环可以用这个来代替:

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

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

此外,看到怎么会有溢出的一个很好的可能性,号码的字符串形式可以用 ss.str访问()。要解决溢出,可能更容易与工作比试图它塞进一个整数。负值应考虑到,也因为这将只工作(和意义)如果第一个值是否定的。

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.

这篇关于转换一个整数数组成数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆