Monday, December 14, 2009

Convert String

Example fo class to convert string in numeric type (int, short int, float, ecc.)

#include

using namespace std;

class Conversion
{
public:
static bool toInt(const char * value, int &returned);
static bool toUShortInt(const char *value, unsigned short &returned);
template static bool fromString(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&));
};





template
bool Conversion::fromString(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}



bool Conversion::toInt(const char *value, int &returned)
{
return fromString(returned, std::string(value), std::dec);

}

bool Conversion::toUShortInt(const char *value, unsigned short &returned)
{
return fromString(returned, std::string(value), std::dec);
}

No comments: