Piotr Wasilewicz - 1 month ago 11
C++ Question

# How to convert string into array of integers with determined width

I need to convert string (for instance "1234567890") to array of integers but width of element is determined by user. So:

if user passed 1 it will be: 1 2 3 4 5 6 7 8 9 0

for 2 I will have an array: 12 34 56 78 90

3: 1 234 567 890

4: 12 3456 7890

etc.

What I tried:

``````#include <iostream>

using namespace std;

int main()
{
string textNumber;
int size;
cin >> textNumber;
cin >> size;

int length = textNumber.length();
int lenghtOfArray = length / size + (length % size ? 1 : 0);
int myArray[lenghtOfArray] = {0};
int move = lenghtOfArray- (size * lenghtOfArray - length);
int copySize = size;
int k = 0;

for(int i=0; i < length;i++) {
if(--copySize && !move){
myArray[k] += (int)textNumber[i]-48;
} else {
myArray[k] += (int)textNumber[i]-48;
++k;
copySize = size;
if(move) --move;
continue;
}
myArray[k] *= 10;
}

myArray[k] += (int)(textNumber[0]-48);

for(int i=0; i < lenghtOfArray; i++) {
cout << myArray[i] << " ";
}
}
``````

but It doesn't work for all cases ( I̶t̶ ̶w̶o̶r̶k̶s̶ ̶o̶n̶l̶y̶ ̶f̶o̶r̶ ̶s̶i̶z̶e̶=̶2̶).

One approach is to use `std::stoi` along with `substr` member function of `std::string` to break string into pieces and parse the results:

``````cin >> s;
cin >> size;
int len = s.length();
int count = (len+size-1) / size;
vector<int> res(count);
int pos = count-1;
while (s.length() > size) {
res[pos--] = stoi(s.substr(s.length()-size));
s = s.substr(0, s.length()-size);
}
if (s.length()) {
res[0] = stoi(s);
}
``````

Note that you need to use `std::vector<int>` instead of an array, because C++ standard does not allow variable-length arrays (g++ offers it as a popular extension).

Demo.