setw

I am trying to create columns. The code setw works for the first 2 outputs, however on the third output it does not effect that text at all, while the code is the exact same as the 2 prior.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>
using namespace std;

int main()

{

	cout <<                  "Noahs Horse Yard\n"; 
	cout <<    "_____________________________________________________________________\n";
	
	cout.setf(ios::left);
	cout.width(20);     cout << "Horse type";
	cout.width(20);     cout << " Minimum Optimum weight";
	cout.width(20);		cout << "Maximum Optimum Weight\n";

	cout << "________________________________________________________________________\n";








	system("PAUSE");
	return 0;
}
Last edited on
The width()/setw() manipulators will only add "spaces" when the variable has fewer characters than the width() value. Since both the Minimum and Maximum text has over 20 characters the width() call doesn't affect the output.

By the way you can use setw() in conjunction with setfill() to add your dashes.
1
2
3
4
5
6
7
8
int main()
{
    cout << setfill('-') << setw(50) << ' '  << setfill(' ') << endl;
    cout << left << setw(20) << "Horse type";
    cout << setw(25) << "Minimum Optimum Weight";
    cout << setw(25) << "Maximum Optimum Weight" << endl;
    cout << right << setfill('-') << setw(50) << ' ' << '\n' << setfill(' ');
}


And remember that both setfill() and left/right are "sticky", meaning that these settings stay in effect until you change them again.

Topic archived. No new replies allowed.