Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert string to an int array using stoi() && substr()

im triying to convert an string to an integer and save those numbers into an array, i tried like this

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
    int number[5];
    string input;
    //numbers
    cout << "type sonme numbers"<<endl;
    cin >> input;
    for(int i = 0 ; i<= 4; i++){
        number[i] = stoi(input.substr(i,i),0,10);
        cout << number[i];
    }
    return 0;
}

when i run it this error comes out:

terminate called after throwing an instance of ‘std::invalid_argument’
what(): stoi

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your first loop is asking for a substring beginning at index 0, with length 0, so you’re passing an empty string to stoi. Even if you in fact provided valid inputs (a string of at least eight digits, so you could call .substr(4, 4) on it and get useful results), the first loop always tries to parse the empty string and dies. Don’t do that.

It’s unclear what the goal here is. If you meant to parse each digit independently, then what you wanted was:

number[i] = stoi(input.substr(i, 1), 0, 10);

which would parse out five sequential length one substrings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading