Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 386
barak manos Avatar asked Mar 21 '23 09:03

barak manos


1 Answers

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

std::stoi(str)

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

like image 56
Joseph Mansfield Avatar answered Mar 31 '23 14:03

Joseph Mansfield