C++ equivalent of sprintf?

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

What is the C++ equivalent of sprintf?


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

Update, August 2019:

It looks like C++20 will have std::format. The reference implementation is {fmt}. If you are looking for a printf() alternative now, this will become the new "standard" approach and is worth considering.

Original:

Use Boost.Format. It has printf-like syntax, type safety, std::string results, and lots of other nifty stuff. You won't go back.


sprintf works just fine in C++.