我很难将一个字符串转换成整数数组。

时间:2022-09-01 22:25:15

Here is my code hitherto:

这是我迄今为止的代码:

(assuming the string is less than 10 digits)

(假设字符串小于10位)

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!

感谢任何帮助!

1 个解决方案

#1


0  

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;

}

#1


0  

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;

}