setw

Hello,
I just needed help on spacing between columns. What is the easiest way to do that? I need to create like 10 spaces between the first row and then 2 spaces the next? Here is the code to what I have, but it's just bunching everything together.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include <iostream>
 #include <iomanip> 
 using namespace std; 
int main()
{
//format the output for money
 cout.setf(ios::fixed); // no scientific notation
 cout.setf(ios::showpoint); // always show the decimal point
 cout.precision (2); //showing 2 decimal points

//display the first row
 cout << "\tItem" << setw(10) << "Projected \n"; 

//display the second row
  cout << "==================" << setw(2) << "============ \n"; 
return 0; 
}
just bunching everything together.
"\tItem"
the tab before "Item" is pushing it to the right, play around with something like this perhaps:
1
2
 cout << std::left << std::setfill('*') << setw(10) << "Item" <<
    std::left << std::setfill('*') << setw(15) << "Projected" << "\n";
closed account (48T7M4Gy)
For the heading and underline the easiest way to handle it is, unless they vary under the program, by hard coding.

1
2
 cout << "Item                 Projected\n";
 cout << "==============================\n";


If they have to be repeated (the line often has to be repeated) just assign the heading lines to string variables.

Then all you do is use setw to line up things in columns as you want:

cout << setw(10) << item << setw(4) << projected; as required for a column of 10 and a column of 4, with right, left etc etc added as needed.

Last edited on
Thanks guys!
Topic archived. No new replies allowed.