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

Time:07-06

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

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related