将整数数组转换为数字 [英] Converting an Integer Array into a Number
问题描述
认为我有一个这样的整数数组:
Think I have an integer array like this:
a[0]=60; a[1]=321; a[2]=5;
现在我想把这个数组整个转换成一个整数,比如int b
运行代码后变成603215.
now I want to convert the whole of this array into an integer number, for example int b
become 603215 after running the code.
怎么做?
推荐答案
使用 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屋!