3

I want to get the int from the string, without using the int type directly to get advantages from getline() but somehow I get an error if the input is not an actual int.

#include <iostream>
#include <string>

using namespace std;

int main (int argc, char** argv)
{
    string word = {0};

    cout << "Enter the number 5 : ";

    getline(cin, word);

    int i_word = stoi(word);

    cout << "Your answer : " << i_word << endl;

    return 0;
}

When the user input is 5 (or any other int) the output is :

Enter the number 5 : 5
Your answer : 5

When the user input is either ENTER or any other letter, word, etc... :

Enter the number 5 : e
terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi
Abandon (core dumped)
Amin NAIRI
  • 2,292
  • 21
  • 20

1 Answers1

4

It's called exception handling:

try
{
    int i_word = stoi(word);

    cout << "Your answer : " << i_word << endl;
} 
catch (const std::invalid_argument& e)
{
    cout << "Invalid answer : " << word << endl;
}
catch (const std::out_of_range& e)
{
    cout << "Invalid answer : " << word << endl;
}
RvdK
  • 19,580
  • 4
  • 64
  • 107