Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

io

iomanip

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.

like image 957
CroCo Avatar asked Sep 18 '17 06:09

CroCo


4 Answers

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;
like image 79
Yunnosch Avatar answered Oct 24 '22 03:10

Yunnosch


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;
like image 42
James Maa Avatar answered Oct 24 '22 03:10

James Maa


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 '%'.

like image 29
gsamaras Avatar answered Oct 24 '22 04:10

gsamaras


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

like image 26
Basile Starynkevitch Avatar answered Oct 24 '22 04:10

Basile Starynkevitch