Search code examples
c++ioiomanip

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


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.


Solution

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