Mateusz Loskot :: hacking on, working out, living up

Save formatted data into std::string

17 Aug 2006 | mloskot

Following short C++ snippet presents how to format number using string stream and save it to std::string object. It is an equivalent to the sprintf function from C library.

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>

int main()
  const long num(789);

  // Format
  std::ostringstream os;
  os << std::setw(9)
       << std::setfill('0')
       << std::right
       << num;

  // Save
  std::string data(os.str());

  // Display
  std::cout << data << std::endl;

  return 0;
Fork me on GitHub