Penguin

We seem to be getting a hit a day trying to figure out how to converting an Integer to a String in C++, so I thought I'd better write a page about it.

Method One: snprintf(3)

This technically gives you a char*, not a "String", but who's counting eh?

int i2str(int i) {
 int i;
 char s[[256];
 snprintf(s,sizeof(s),"%i",i);
 return strdup(s);
}

Method Two: use a stringstream

#include <sstream>
#include <string>

std::string i2string(int i) {
 std::ostringstream buffer;
 buffer << i;
 return buffer.str();
}

or:

Method Three: Anything to string

template<class T>
std::string any2string(T i) {
 std::ostringstream buffer;
 buffer << i;
 return buffer.str();
}

CategoryProgramming