-
Aligning text
Okay so I should know this (and I know I did at one time) but:
I want to print text to the screen like this: (the underlines are spaces, only way I could get the spacing right)
5_____6 _____3
10____2______1
but using setw(x) it looks like this:
5_____6______3
10_____2______1
using setw the amount of spaces always starts from the last character. I'm assuming that setw isn't the correct command, so what am I missing here?
-
setw works kinda like a tab... if you setwidth to 5, the last character of the next output will be put in the 5th space... if there's too many characters (more than 5) it will just put it directly next to the last thing...
Code:
...
cout<<hello<<setw(10)<<world;
...
output: "hello.....world"
Code:
...
cout<<hello<<setw(3)<<world;
...
output: "helloworld"
all of the '.' in the first output are spaces...
-
>using setw the amount of spaces always starts from the last character
This works for me on multiple compilers (G++, VC++, DevC++, Borland C++):
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int i = 5;
cout<< left << setw(i) << 5 << setw(i) << 6 << setw(i) << 3 <<endl;
cout<< left << setw(i) << 10 << setw(i) << 2 << setw(i) << 1 <<endl;
}
Code:
Output:
5 6 3
10 2 1
-
Thanks Prelude that works great. :)
-
Why not put setw(5) instead of setw(i).
-
>Why not put setw(5) instead of setw(i).
What if you decide to use something else instead of 5?