C++ convert to/from string

One of the majority deficiencies in C++ has always been the lack of a simple standard method to convert to and from strings to numeric types. The C language extensions atoi and itoa are often available, but obviously only deal with integer types, and are non-standard. Cx11 appears to introduce these features in stoi and to_string methods.

However, adapted from the C++ FAQ this is the stringify.h header I’ve always used. It conveniently templatises the conversion (at least one example of templates not causing pain and suffering!). So you can convert a string to a double as:

double d = convertTo<double>(mystring);

Or convert a double to a string with:

string s = stringify(d);

#include <sstream>
#include <iostream>
#include <string>
#include <stdexcept>

#ifndef STRINGIFY_H
#define STRINGIFY_H

class BadConversion : public std::runtime_error {
public:
BadConversion(const std::string& s)
: std::runtime_error(s) {}
};

template<class _type>
inline std::string stringify(_type x)
{
std::ostringstream o;
if (!(o << std::fixed << x))
throw BadConversion("stringify()");
return o.str();
}

template<class _type>
inline _type convertTo(const std::string& s)
{
std::istringstream i(s);
_type x;
if (!(i >> x))
throw BadConversion("convertTo(\"" + s + "\")");
return x;
}

#endif

Comments are closed.