C++ equivalent of sprintf?

lital maatuk picture lital maatuk · Feb 13, 2011 · Viewed 86k times · Source

I know that std::cout is the C++ equivalent of printf.

What is the C++ equivalent of sprintf?

Answer

Vijay Mathew picture Vijay Mathew · Feb 13, 2011

std::ostringstream

Example:

#include <iostream>
#include <sstream> // for ostringstream
#include <string>

int main()
{
  std::string name = "nemo";
  int age = 1000;
  std::ostringstream out;  
  out << "name: " << name << ", age: " << age;
  std::cout << out.str() << '\n';
  return 0;
}

Output:

name: nemo, age: 1000