Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error while trying to get the int from a string

Tags:

c++

string

int

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)
like image 842
Amin NAIRI Avatar asked Mar 04 '26 09:03

Amin NAIRI


1 Answers

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;
}
like image 172
RvdK Avatar answered Mar 06 '26 22:03

RvdK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!