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.
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;
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;
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 '%'
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With