Convert Stirng into int array

I need code for this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# include <iostream>
# include <string>
using namespace std;
int main()
{
	string s ("1300000000000900000000100006548");
        int arr[5]={0};
    /* 
    	   arr[0]= 130000000
	   arr[1]= 000090000     
	   arr[2]= 000010000
	   arr[3]= 6548
	   arr[4]=  0
	   
	   */   
	return 0;
}
Last edited on
Hello zain ahmad,

If you mean to break up the string that way I would use "s.substr()" along with "stoi" to turn it into a number. Both are from the string class. This is untested, but I am thinking:
arr[0] = std::stoi(s.substr(0, 9));

Note: for the second and third elements of the array the leading zeros will be dropped.

I was thinking of a foe loop, but not all numbers are the same size. The last two are shorter which makes a for loop more difficult to code and not something that would fit every case unless the original string is always the same size.

I will load up the program and test it out shortly.

Hope that helps,

Andy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

int main()
{
   const int LEN = 9;
   const int DIM = 5;
   string s{ "1300000000000900000000100006548" };
   vector<int> A;

   int size = s.size();
   for ( int i = 0; i < size; i += LEN )
   {
      int len = LEN;   if ( i + len >= size ) len = size - i;
      A.push_back(    stoi( s.substr( i, len ) )    );
   }

   // If you want a minimum number ...
   while ( A.size() < DIM ) A.push_back( 0 );

   // If you don't want the leading zeros then remove the fill( '0' ) below ...
   for ( int e : A ) cout << setfill( '0' ) << setw( LEN ) << e << '\n';
}


130000000
000090000
000010000
000006548
000000000



If you are stuck with a fixed-size standard array then try:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

int main()
{
   const int LEN = 9;
   const int DIM = 5;
   string s{ "1300000000000900000000100006548" };
   int A[DIM] = { 0 };

   int size = s.size();
   for ( int i = 0, index = 0; i < size && index < DIM; i += LEN, index++ )
   {
      int len = LEN;   if ( i + len >= size ) len = size - i;
      A[index] = stoi( s.substr( i, len ) );
   }

   for ( int e : A ) cout << e << '\n';
}
130000000
90000
10000
6548
0
Last edited on
Topic archived. No new replies allowed.