C++: Convert integer to string?

Using only ANSI Standard C++, what is the easiest way to convert an interger to a string without using sprintf or any of its variations?

<clip> nevermind, I read your question wrong.

If you mean “without using the old C I/O libraries,” then <stringstream>. Or do you mean “without any external libraries”?

Definitely stringstream:

#include <sstream>
#include <string>
#include <iostream>

int main(int argc, char** argv)
  int input = 5;
  std::string buffer;
  std::stringstream ss;
  ss << input;
  ss >> buffer;
  std::cout << buffer << std::endl;
  return 0;

That should work.

I can show you how to do it in C…


One of my favorite utility templates:

#include <sstream>
template<typename Type_t>
std::string ToStr(const Type_t& T)
  std::ostringstream sout; sout<<T; return sout.str();

Will convert any printable type into a string.

Not typesafe, nor is it standard ANSI C (it won’t work with some gcc’s).

Ah, sorry. It’s been a while. These days I’d write it like “[int].ToString();” or “string s = Convert.ToString([int variable]);” :wink: