stoi

Feb 5, 2017 at 2:32am
hey, just some question, what if stoi has an error ?
does it return boolean like sstream ?
because I failed at using stoi for something I succeed with sstream.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string input;
    cin >> input;
    if (stoi(input) == true) cout << "you entered integer\n";
    else cout << "you entered random sh*t\n";
    cout << "press enter to exit\n";
    cin.ignore();
}
Feb 5, 2017 at 2:38am
> what if stoi has an error ?

It throws.
std::invalid_argument if no conversion could be performed
std::out_of_range if the converted value would fall out of the range of int
http://en.cppreference.com/w/cpp/string/basic_string/stol

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>

int main()
{
    std::string input;
    std::cin >> input;

    try
    {
        std::size_t pos ;
        std::stoi( input, std::addressof(pos) ) ;

        if( pos == input.size() ) std::cout << "you entered an integer\n" ;
        else std::cout << "the first part of what you entered is an integer\n";
    }

    catch( const std::invalid_argument& ) { std::cout << "bad input\n" ; }
    catch( const std::out_of_range& ) { std::cout << "that number is too big / too small\n" ; }
}
Last edited on Feb 5, 2017 at 2:48am
Feb 5, 2017 at 5:12am
thanks :)
Topic archived. No new replies allowed.