Ins*_*Man 5 c++ arrays integer
我想我有一个像这样的整数数组:
a[0]=60; a[1]=321; a[2]=5;
Run Code Online (Sandbox Code Playgroud)
现在我想将整个数组转换为整数,例如int b在运行代码后变为603215.
怎么做?
chr*_*ris 12
使用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
}
Run Code Online (Sandbox Code Playgroud)
请注意,在C++ 11中,稍微丑陋的循环可以替换为:
for (int i : arr)
ss << i;
Run Code Online (Sandbox Code Playgroud)
另外,看看溢出的可能性很大,可以使用数字的字符串形式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;
}
}
Run Code Online (Sandbox Code Playgroud)
finalNumber有一个结果:603215
Concat将所有数字作为字符串,然后将其转换为数字
#include <string>
int b = std::stoi("603215");
Run Code Online (Sandbox Code Playgroud)