terminate called after throwing instance of std::invalid_argument C++

In this article we will resolve the c++ issue related to “terminate called after throwing an instance of ‘std::invalid_argument’ what(): stoi“.

Introduction

Suppose you have a string and you want to interpret the signed integer from it using c++, then you may use any of these functions –

Their method signatures are as follows –

int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );

long stol( const std::string& str, std::size_t* pos = nullptr, int base = 10 );

long long stoll( const std::string& str, std::size_t* pos = nullptr, int base = 10 );

Protocols for valid input string

These methods can convert an input string to unsigned number. But for that the string needs to follow some protocols like –

  1. It should start with either blank spaces, +/-, numbers or alphabets depending on base value.
  2. Range of the valid base values are – 0 and 2 to 36.
  3. If it starts with 0 then base needs to be 0 or 8.
  4. If it starts with 0x or 0X then base needs to be 0 or 16.
  5. Valid numbers and alphabets in string according to base values are –
Base Value Valid Range
2 {0-1}
3 {0-2}
4 {0-3}
5 {0-4}
6 {0-5}
7 {0-6}
8 {0-7}
9 {0-8}
10 {0-9}
11 {0-9, Aa}
12 {0-9, Aa-Bb}
13 {0-9, Aa-Cc}
14 {0-9, Aa-Dd}
15 {0-9, Aa-Ee}
16 {0-9, Aa-Ff}
17 {0-9, Aa-Gg}
18 {0-9, Aa-Hh}
19 {0-9, Aa-Ii}
20 {0-9, Aa-Jj}
21 {0-9, Aa-Kk}
22 {0-9, Aa-Ll}
23 {0-9, Aa-Mm}
24 {0-9, Aa-Nn}
25 {0-9, Aa-Oo}
26 {0-9, Aa-Pp}
27 {0-9, Aa-Qq}
28 {0-9, Aa-Rr}
29 {0-9, Aa-Ss}
30 {0-9, Aa-Tt}
31 {0-9, Aa-Uu}
32 {0-9, Aa-Vv}
33 {0-9, Aa-Ww}
34 {0-9, Aa-Xx}
35 {0-9, Aa-Yy}
36 {0-9, Aa-Zz}

Exceptions in stoi, stol, stoll

There are two kinds of exceptions –

  1. std::invalid_argument
  2. std::out_of_range

std::invalid_argument

Any string that is not following the above protocol will raise std::invalid_argument exception. So, few of the examples are –

std::size_t pos{};

std::stoi("something 43", &pos)

Error because the string starts with alphabets but the base is 10. In the table above we indicated the valid values for all the base values. In stoi, stol, stoll functions we have base 10 by default.

std::stoi("f43", &pos, 10)

Error because the string starts with f which indicates the hexadecimal number but we provided the base as 10.

std::stoi("A45G6", &pos, 16)

// Output - 2629

Here the output will be 2629 as the decimal value of A45 with base 16. Here G6 is truncated because G is not a valid base 16 character. Hence the stoi function took every valid digits before G.

std::out_of_range

You will get this error when the input value is bigger than what function can support. If you provide a numeric string to stoi which returns int value then the string needs to have number smaller than max-int (2147483647).

Solution

The solution to this problem is to follow the input string protocol as described above. Otherwise you will get either of the two exceptions.