Question

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?

Was it helpful?

Solution

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

std::stoi(str)

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

OTHER TIPS

In there's a number of numeric conversion functions defined in the std::string class itself:

Numeric conversions
stoi (C++11)
stol (C++11)
stoll (C++11)

converts a string to a signed integer

stoul (C++11)
stoull (C++11)

converts a string to an unsigned integer

stof (C++11)
stod (C++11)
stold (C++11)

converts a string to a floating point value

As for pre c++11 standards, I can't see any disadvantages from your template function sample.

Yyou can use conversion functions Strtol() Strtoul() However in C++11 , you have got answers above.

#include <sstream>
template <typename T>
inline bool StringToNumber(const std::string& sString, T &tX)
{
    std::istringstream iStream(sString);
    return !(iStream >> tX).fail();not
}

Then call

double num{};
StringToNumber(std::string{"580.8"}, num);

float fnum{};
StringToNumber(std::string{"5e+1.0"}, fnum);

#include <iostream>
#include <string>

int main() {

    std::string str = "123";
    int num;

    // using stoi() to store the value of str1 to x
    num = std::stoi(str);

    std::cout << num;

    return 0;
}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top