I am using setw from #include <iomanip> library to format the output and it works just fine...

Par exemple.

cout<<std::setiosflags ( std::ios_base::right ) << std::setw ( 20 ) << "---------025125222" << std::endl;

However, I wish to format the same output as a STRING.

So instead of doing cout, I want to assign it to a string? Don't ask why, I just need to.

Question is how?

An example would be great.

Edited 6 Years Ago by iamthwee: n/a

The easiest way is to load it in a stringstream first, so you can use al your stream-functions.

untested example:

std::stringstream a_stream;
    a_stream << std::setiosflags ( std::ios_base::right ) << std::setw ( 20 ) << "---------025125222" << std::endl;
    std::string the_string = a_stream.str();
    std::cout << the_string;


Also I just tried the following which appears to work.

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

int main()
  std::ostringstream oss;

  for (int i = 1; i < 15; i++)
    oss << std::setw(3) << i << '\n';

  std::string output(oss.str());
  std::cout << output ;

  return 0;
This question has already been answered. Start a new discussion instead.