stringstream integers into arrays

Hello, i have this code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    int num;
    string s = "9876";
    stringstream ss(s);

    
    ss >> num;
    cout << num << endl;
    
    cin.get();
    return 0;
}

How do i make it so that it assigns the string into an array
for example

num[0]=9
num[1]=8
num[2]=7
num[3]=6
1
2
3
4
int num[4] = {0};
string s = "9876";
for (int i = 0; i < s.size(); i++)
   num[i] = s[i]-'0';
?
thanks it worked perfectly.
i tried doing
num[i] = atoi(s[i].c_str());

but that didnt work, so what does the
num[i] = s[i]-'0';

actually do to make the difference?
You wrote that line without thinking about types. s is a string, s[i] is a char. char has no method c_str(). If you wrote s.c_str()[i] it would be fine and work exactly like s[i]. The argument that atoi wants is char*, while you only give it char.

What my line does is map ascii values of digits '0', '1', '2', ... = 48, 49, 50, ... to actual numbers 0, 1, 2, ..., obviously by subtracting '0' = 48.
Topic archived. No new replies allowed.