c++stlstring-conversion

Converting a string to a number in C++


I'm seeing a lot of options for converting a string to a number in C++.

Some of which are actually recommending the use of standard C functions such as atoi and atof.

I have not seen anyone suggesting the following option, which relies solely on C++ STL:

int Str2Num(const string& str) // can be called with a 'char*' argument as well
{
    int num;
    istringstream(str)>>num;
    return num;
}

Or more generally:

template <typename type>
type Str2Num(const string& str) // can be called with a 'char*' argument as well
{
    type num;
    istringstream(str)>>num;
    return num;
}

What are the disadvantages in the above implementation?

Is there a simpler / cleaner way to achieve this conversion?


Solution

  • Since C++11, we have had std::stoi:

    std::stoi(str)
    

    There is also std::stol and std::stoll.