std::lexical_cast - is there such a thing?

C++ParsingCastingStdC++ Standard-Library

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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.

Solution 3 - C++

There's no std::lexical_cast, but you can always do something similar with stringstreams:

template <typename T>
T lexical_cast(const std::string& str)
{
    T var;
    std::istringstream iss;
    iss.str(str);
    iss >> var;
    // deal with any error bits that may have been set on the stream
    return var;
}

Solution 4 - C++

No it's a pure Boost thing only.

Solution 5 - C++

If you don't want boost then a lightweight library called fmt implements the following:

// Works with all the C++11 features and AFAIK faster then boost or standard c++11
std::string string_num = fmt::format_int(123456789).str(); // or .c_str()

More examples from the official page.

Accessing arguments by position:

format("{0}, {1}, {2}", 'a', 'b', 'c');
// Result: "a, b, c"
format("{}, {}, {}", 'a', 'b', 'c');
// Result: "a, b, c"
format("{2}, {1}, {0}", 'a', 'b', 'c');
// Result: "c, b, a"
format("{0}{1}{0}", "abra", "cad");  // arguments' indices can be repeated
// Result: "abracadabra"

Aligning the text and specifying a width:

format("{:<30}", "left aligned");
// Result: "left aligned                  "
format("{:>30}", "right aligned");
// Result: "                 right aligned"
format("{:^30}", "centered");
// Result: "           centered           "
format("{:*^30}", "centered");  // use '*' as a fill char
// Result: "***********centered***********"

Replacing %+f, %-f, and % f and specifying a sign:

format("{:+f}; {:+f}", 3.14, -3.14);  // show it always
// Result: "+3.140000; -3.140000"
format("{: f}; {: f}", 3.14, -3.14);  // show a space for positive numbers
// Result: " 3.140000; -3.140000"
format("{:-f}; {:-f}", 3.14, -3.14);  // show only the minus -- same as '{:f}; {:f}'
// Result: "3.140000; -3.140000"

Replacing %x and %o and converting the value to different bases:

format("int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
// Result: "int: 42;  hex: 2a;  oct: 52; bin: 101010"
// with 0x or 0 or 0b as prefix:
format("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}", 42);
// Result: "int: 42;  hex: 0x2a;  oct: 052;  bin: 0b101010"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsmallBView Question on Stackoverflow
Solution 1 - C++Lightness Races in OrbitView Answer on Stackoverflow
Solution 2 - C++CharlesBView Answer on Stackoverflow
Solution 3 - C++lukeView Answer on Stackoverflow
Solution 4 - C++Some programmer dudeView Answer on Stackoverflow
Solution 5 - C++SLCView Answer on Stackoverflow