How to convert std::wstring to numeric type(int, long, float)?

Hyden picture Hyden · Feb 25, 2011 · Viewed 29.7k times · Source

What's the best way to convert std::wstring to numeric type, such as int, long, float or double?

Answer

Howard Hinnant picture Howard Hinnant · Feb 25, 2011

C++0x introduces the following functions in <string>:

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);

idx is an optionally null pointer to the end of the conversion within str (set by the conversion function).