Save formatted data into std::string

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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>