If you cannot use std::to_string
from C++11, you can write it as it is defined on cppreference.com:
std::string to_string( int value )
Converts a signed decimal integer to a string with the same content as whatstd::sprintf(buf, "%d", value)
would produce for sufficiently large buf.
Implementation
#include <cstdio>
#include <string>
#include <cassert>
std::string to_string( int x ) {
int length = snprintf( NULL, 0, "%d", x );
assert( length >= 0 );
char* buf = new char[length + 1];
snprintf( buf, length + 1, "%d", x );
std::string str( buf );
delete[] buf;
return str;
}
You can do more with it. Just use "%g"
to convert float or double to string, use "%x"
to convert int to hex representation, and so on.