Convert String to Integer or Double
As we know, C++ standard library provide several standar functions to convert string to int or double.
- atoi(): Convert a string to an integer;
- atol(): Convert a string to long integer;
- atof(): Convert a string to a double;
At here, I provide an alternative way to do all of the tasks in one function. You could use the following template function that use istringstreams for converting string to int or double.
//---------------------------------------------------
// Convert string to typename T (e.g. int, double etc)
// e.g: int d = FromString<int>( s );
//---------------------------------------------------
#include <sstream>
template<typename T>
T FromString(const std::string& s)
{
std::istringstream is(s);
T t;
is >> t;
return t;
}
Overloaded istream:: operator>>
Extracts data from the stream and stores it in the parameter passed (right-value).
class members:
istream& operator>> (bool& val );
istream& operator>> (short& val );
istream& operator>> (unsigned short& val );
istream& operator>> (int& val );
istream& operator>> (unsigned int& val );
istream& operator>> (long& val );
istream& operator>> (unsigned long& val );
istream& operator>> (float& val );
istream& operator>> (double& val );
istream& operator>> (long double& val );
istream& operator>> (void*& val );
istream& operator>> (streambuf& sb );
istream& operator>> (istream& ( *pf )(istream&));
istream& operator>> (ios& ( *pf )(ios&));
istream& operator>> (ios_base& ( *pf )(ios_base&));
external operator>> overloaded functions:
istream& operator>> (istream& is, char& ch );
istream& operator>> (istream& is, signed char& ch );
istream& operator>> (istream& is, unsigned char& ch );
istream& operator>> (istream& is, char* str );
istream& operator>> (istream& is, signed char* str );
istream& operator>> (istream& is, unsigned char* str );