将整数数组转换为数字 [英] Converting an Integer Array into a Number

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

问题描述

想想我有一个整数数组这样: a [0] = 60; a [1] = 321。 a [2] = 5; 现在我想将整个数组转换为整数,例如 int b 代码。如何做?

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天全站免登陆