C++0x ライブラリ - Numeric Conversion

atoiのような標準の型変換関数に、std::basic_stringを引数にするものが追加される

string str = "abc";

int value = atoi(str.c_str());
int value = stoi(str);


これらの関数は内で定義される

int stoi(const string& str, size_t *idx = 0, int base = 10);

long stol(const string& str, size_t *idx = 0, int base = 10);

unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);

long long stoll(const string& str, size_t *idx = 0, int base = 10);

unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);

float stof(const string& str, size_t *idx = 0);

double stod(const string& str, size_t *idx = 0);

long double stold(const string& str, size_t *idx = 0);

string to_string(long long val);

string to_string(unsigned long long val);

string to_string(long double val);
int stoi(const wstring& str, size_t *idx = 0, int base = 10);

long stol(const wstring& str, size_t *idx = 0, int base = 10);

unsigned long stoul(const wstring& str, size_t *idx = 0, int base = 10);

long long stoll(const wstring& str, size_t *idx = 0, int base = 10);

unsigned long long stoull(const wstring& str, size_t *idx = 0, int base = 10);

float stof(const wstring& str, size_t *idx = 0);

double stod(const wstring& str, size_t *idx = 0);

long double stold(const wstring& str, size_t *idx = 0);

wstring to_wstring(long long val);

wstring to_wstring(unsigned long long val);

wstring to_wstring(long double val);


なんで今までなかったのか

#include <sstream>

template <class Type>
inline std::string to_string(const Type& target)
{
    std::stringstream interpreter;
    interpreter << target;
    return interpreter.str();
}

template <class Type>
inline std::wstring to_wstring(const Type& target)
{
    std::wstringstream interpreter;
    interpreter << target;
    return interpreter.str();
}


// string to numeric
inline int    stoi(const std::string& str) { return atoi(str.c_str()); }
inline long   stol(const std::string& str) { return atol(str.c_str()); }
inline float  stof(const std::string& str) { return static_cast<float>(atof(str.c_str())); }
inline double stod(const std::string& str) { return atof(str.c_str()); }

// wstring to numeric
inline int    stoi(const std::wstring& str) { return _wtoi(str.c_str()); }
inline long   stol(const std::wstring& str) { return _wtol(str.c_str()); }
inline float  stof(const std::wstring& str) { return static_cast<float>(_wtof(str.c_str())); }
inline double stod(const std::wstring& str) { return _wtof(str.c_str()); }

C++0x言語拡張まとめ