Integer to string template function

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

One thought on “Integer to string template function

  1. 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:
    The correct way is this:
    gcc this.cpp -o this -lstdc++
    Thank you for this tutorial , but you can more ;)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: