equivalent of atoi

boost::lexical_cast is your friend

#include <string>
#include <boost/lexical_cast.hpp>

int main()
{
    std::string s = "123";
    try
    {
       int i = boost::lexical_cast<int>(s); //i == 123
    }
    catch(const boost::bad_lexical_cast&)
    {
        //incorrect format   
    }
}

You can use the Boost function boost::lexical_cast<> as follows:

char* numericString = "911";
int num = boost::lexical_cast<int>( numericString );

More information can be found here (latest Boost version 1.47). Remember to handle exceptions appropriately.


Without boost:
stringstream ss(my_string_with_a_number); int my_res; ss >> my_res;
About as annoying as the boost version but without the added dependency. Could possibly waste more ram.


If you don't want to use Boost, C++11 added std::stoi for strings. Similar methods exist for all types.

std::string s = "123"
int num = std::stoi(s);

Unlike atoi, if no conversion can be made, an invalid_argument exception is thrown. Also, if the value is out of range for an int, an out_of_range exception is thrown.

Tags:

C++

Atoi