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?
Use a 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
}
Note that in C++11 that mildly ugly loop can be replaced with this:
for (int i : arr)
ss << i;
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.
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 has a result: 603215
length member. It's typically better to use std::vector instead, as it offers the functionality. 2. a should be arr.Concat all the numbers as a string and then convert that to number
#include <string>
int b = std::stoi("603215");
This algorithm will work:
stringstreamsolution seems simpler.