Converting string to integer array in C++

For Example,
it the entered string is: 0324152397
I want it to get stored in an array like-[0] [3] ...[7].
Secondly the string entered may be of any length that is defined only at run time.
So, I also need to calculate string length.
How could I do that.
You have to use a dynamic array or a stl container then iterate over the string and assign the values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::string const input = "0324152397";

int *array = new int[input.size()];
for(int i = 0; i < input.size(); ++i) //this way might be best for indexing
{
    array[i] = input[i] - '0';
}

//or with container
std::vector<int> vec;
for(char const &it : input)
{
    vec.push_back(it - '0');
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
  cout << "Enter a number: ";
  string s;
  getline( cin, s );

  vector <int> xs( s.begin(), s.end() );
  for (auto& x : xs) x -= '0';

  cout << "The digits you entered are: ";
  for (auto x: xs) cout << x << " ";
  cout << "\n";
}
Topic archived. No new replies allowed.