Convert any integer type, to any c++ string type (char or wchar_t) using this template function:
#include <string>
#include <algorithm>
#include <iostream>
template <typename Int_T, typename Char_T>
std::basic_string<Char_T> itoa(Int_T num, int base) {
std::basic_string<Char_T> buf;
buf.push_back(0);
bool neg;
if (num < 0) { neg = true; num *= -1; }
int i, j;
Char_T digits[36];
for (j = 0, i = '0'; i <= '9'; i++, j++) digits[j] = i;
for (i = 'a'; i <= 'z'; i++, j++) digits[j] = i;
do {
buf.push_back(digits[num % base]);
num /= base;
} while (num != 0);
if (neg) buf.push_back('-');
std::reverse(buf.begin(), buf.end());
return buf;
}
int main() {
std::wcout << L"-12 in binary is " <<
itoa<int, wchar_t>(-12, 2) <<
std::endl;
}
Hi.
Your examples is very usefull , but is need to knowing the compiling.
First if we use : gcc this.cpp -o this I got this error:
undefined reference to `__gxx_personality_v0′ collect2: ld returned 1 exit status
So is need to use this option:
-lstdc++
The correct way is this:
gcc this.cpp -o this -lstdc++
Thank you for this tutorial , but you can more ;)