Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::lexical_cast - is there such a thing?

Does the C++ Standard Library define this function, or do I have to resort to Boost?

I searched the web and couldn't find anything except Boost, but I thought I'd better ask here.

like image 783
smallB Avatar asked Nov 09 '11 13:11

smallB


2 Answers

Only partially.

C++11 <string> has std::to_string for the built-in types:

[n3290: 21.5/7]:

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

Returns: Each function returns a string object holding the character representation of the value of its argument that would be generated by calling sprintf(buf, fmt, val) with a format specifier of "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", or "%Lf", respectively, where buf designates an internal character buffer of sufficient size.

There are also the following that go the other way around:

[n3290: 21.5/1, 21.5/4]:

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

However, there's nothing generic that you can use (at least not until TR2, maybe!), and nothing at all in C++03.

like image 121
Lightness Races in Orbit Avatar answered Nov 20 '22 20:11

Lightness Races in Orbit


No it isn't, even in C++11, but it's proposed for inclusion in Technical Report 2, the next set of std library extensions.

like image 19
CharlesB Avatar answered Nov 20 '22 21:11

CharlesB