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

When you encounter an error message stating “terminate called after throwing an instance of ‘std::invalid_argument’ what(): stoi”, it means that there was a problem with using the stoi function in C++. Specifically, this error is related to trying to convert a string to an integer using stoi, and the string provided is not a valid representation of an integer.

The stoi function in C++ is used to convert a string to an integer. However, if the provided string cannot be converted to an integer, it will throw an instance of std::invalid_argument. This typically occurs when the string contains characters that are not numeric, such as letters or symbols.

Here is an example that can produce the mentioned error:

    
      #include <iostream>
      #include <string>

      int main() {
          std::string str = "abc123";
          int num = std::stoi(str);
          std::cout << "Converted number: " << num << std::endl;
          return 0;
      }
    
  

In this example, the string "abc123" cannot be converted to an integer because it contains the characters 'a', 'b', and 'c'. When the stoi function encounters these non-numeric characters, it throws an instance of std::invalid_argument, resulting in the "terminate called after throwing an instance of 'std::invalid_argument' what(): stoi" error message.

Read more

Leave a comment