c++atoi

equivalent of atoi


Is there a function that could replace atoi in c++. I made some research and didn't find anything to replace it, the only solutions would be using cstdlib or implementing it myself


Solution

  • 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.