terminate called after throwing an instance of 'std::invalid_argument'

I want to convert a string to an array of integers. The following is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int main()
{

    string num1="";
    cout<<"enter a number: ";

    cin>>num1;

    int a[10];

    for (int i=0; i<10; i++)
    {
        a[i]=stoi(num1.substr(i,i));
    }
    for (int i=0;i<10;i++)
    {
        cout<<a[i];
    }

    system("pause");
    return 0;
}


The code above causes the following errors,

terminate called after throwing an instance of 'std::invalid_argument'
what (): stoi
Aborted (core dumped)


after running. Could someone help me? Thank you!
What if I enter a number that isn't 10 characters long? What do you even expect line 19 to do?
http://www.cplusplus.com/reference/string/basic_string/substr/
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <vector>
#include <cctype>

int main()
{
    // string num1="";
    std::string num1 ;

    std::cout << "enter a number: ";
    std::cin >> num1 ;

    // int a[10];
    std::vector<int> a ; // http://www.mochima.com/tutorials/vectors.html

    // for (int i=0; i<10; i++)
    for( char c : num1 ) // http://www.stroustrup.com/C++11FAQ.html#for
    {
        // a[i]=stoi(num1.substr(i,i));

        // http://en.cppreference.com/w/cpp/string/byte/isdigit
        if( std::isdigit(c) ) a.push_back( c - '0' ) ;
        else std::cerr << "invalid character '" << c << "\n" ;
    }

    // for(int i=0;i<10;i++)
    for( int digit : a )
    {
        // cout<<a[i];
        std::cout << digit << ' ' ;
    }

    // system("pause");
    std::cout << "\npress enter to quit: " ;
    std::cin.ignore( 1000, '\n' ) ;
    std::cin.get() ;

    // return 0;
}

http://coliru.stacked-crooked.com/a/aa8c39f891f674bf
Thank you! I fixed it. ^^
Topic archived. No new replies allowed.