想我有一个这样的整数数组:
a[0]=60; a[1]=321; a[2]=5;
现在我想将整个数组转换为整数,例如int b
运行代码后变为 603215。
怎么做?
使用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 中,稍微难看的循环可以替换为:
for (int i : arr)
ss << i;
此外,鉴于溢出的可能性很大,数字的字符串形式可以使用ss.str()
. 为了避免溢出,使用它可能比尝试将它塞进一个整数更容易。负值也应该考虑在内,因为这只有在第一个值为负时才有效(并且有意义)。
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 有结果:603215
将所有数字连接为字符串,然后将其转换为数字
#include <string>
int b = std::stoi("603215");
该算法将起作用:
迭代数组并将值转换为字符串。然后连接所有这些并转换回整数。
#include <string>
int a[] = {60, 321, 5};
std::string num = "";
for(auto val : a)
num += a;
int b = std::stoi(num);