Last active
December 21, 2015 06:09
-
-
Save chengluyu/6262131 to your computer and use it in GitHub Desktop.
A well-framed integral value to std::string function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename integral> | |
std::string to_string(integral value, int base = 10, bool lower_case = true) { | |
const char * digit = lower_case ? "0123456789abcedfghijklmnopqrstuvwxyz" | |
: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
assert(2 <= base && base <= 36); | |
std::string str; | |
bool negative = false; | |
if (value < 0) { | |
negative = true; | |
value = -value; | |
} | |
do { | |
str += digit[value % base]; | |
value /= base; | |
} while (value != 0); | |
if (negative) | |
str += '-'; | |
std::reverse(str.begin(), str.end()); | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is it really well-framed?
I don't sure.
But I'd improve it.