j.doe j.doe - 2 months ago 11
C++ Question

I'm having trouble converting a string into an array of integers

Here is my code hitherto:

(assuming the string is less than 10 digits)

string s;
cin >> s;
int array[10];
for(int i=10, j =s.length(); i>0 && j>0; i--,j--){
array[i]=(int)s[j];
}
for(int b=10; b>0;b--){
cout << array[b];
}


thanks for any help!

Answer

You probably wanted to do this:

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string s;
    cin >> s;

    int array[10];

    for(int i=s.length(); i>=0; i--)
    {
        array[i]=s[i]-'0';
    }

    for(int b=0; b<s.length();b++)
    {
        cout << array[b];
    }


    //better way

    int num =stoi (s,nullptr,0); // You can convert the entire string to an int like this.
    cout << endl << num << endl;

}