Member Avatar for iamthwee


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.

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;
Member Avatar for iamthwee


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;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.