c++stringinteger

How can I convert a std::string to int?


I want to convert a string to an int and I don't mean ASCII codes.

For a quick run-down, we are passed in an equation as a string. We are to break it down, format it correctly and solve the linear equations. Now, in saying that, I'm not able to convert a string to an int.

I know that the string will be in either the format (-5) or (25) etc. so it's definitely an int. But how do we extract that from a string?

One way I was thinking is running a for/while loop through the string, check for a digit, extract all the digits after that and then look to see if there was a leading '-', if there is, multiply the int by -1.

It seems a bit over complicated for such a small problem though. Any ideas?


Solution

  • In C++11 there are some nice new convert functions from std::string to a number type.

    So instead of

    atoi( str.c_str() )
    

    you can use

    std::stoi( str )
    

    where str is your number as std::string.

    There are version for all flavours of numbers: long stol(string), float stof(string), double stod(string),... see http://en.cppreference.com/w/cpp/string/basic_string/stol