How to include two calls of >> in one setw?

1.4k views Asked by At

Take this a minimal working example

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{

    cout    << setw(10) << "aaaaaaa"
            << setw(10) << "bbbb"
            << setw(10) << "ccc"
            << setw(10) << "ddd"
            << setw(10) << endl; 

    for(int i(0); i < 5; ++i){

        char ch = ' ';
        if ( i == 0 )
            ch = '%';
        cout << setw(10) << i
             << setw(10) << i << ch
             << setw(10) << i
             << setw(10) << i
             << setw(10) << endl;
    }
    return 0;
}

The output is

   aaaaaaa      bbbb       ccc       ddd
         0         0%         0         0
         1         1          1         1
         2         2          2         2
         3         3          3         3
         4         4          4         4

What I would like to do is to include << i << ch in one field of setw(10) so that columns are aligned properly.

4

There are 4 answers

4
James Maa On BEST ANSWER

probably combine i and ch in one string, setw wouldn't accept this behavior natively

try this snippet

 cout << setw(10) << i
      << setw(10) << std::to_string(i) + ch;
1
gsamaras On

You need to concatenate them into one string, like this:

#include <string>
cout << setw(10) << std::to_string(i) + ch;

in general.

But if you know that i is one character you could use:

cout << setw(9) << i << ch;

which might the case for you, since i seems to be ' ' or '%'.

0
Basile Starynkevitch On

I'm not sure to understand your need.

You could use some std::ostringstream like e.g.

 std::ostringstream os;
 os << i << ch << std::flush;
 std::cout << setw(10) << os.str();

You could build a string, like James Maa answered

1
Yunnosch On

Since we are looking at either ' ' or '%' you can simply calculate statically.

cout << setw(10) << i
     << setw( 9) << i << ch
     << setw(10) << i
     << setw(10) << i
     << setw(10) << endl;