Skip to content

Instantly share code, notes, and snippets.

@chengluyu
Last active December 21, 2015 06:09
Show Gist options
  • Save chengluyu/6262131 to your computer and use it in GitHub Desktop.
Save chengluyu/6262131 to your computer and use it in GitHub Desktop.
A well-framed integral value to std::string function.
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;
}
@chengluyu
Copy link
Author

Is it really well-framed?
I don't sure.
But I'd improve it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment