Text Alignment Using Setw()

Hi, I'm trying to align text on the console and I'm having trouble getting everything aligned to where it should be.

I have a program right now that's using an array of class objects and I'm trying to print it all out to look like a nice menu.

My code for the alignment.

1
2
3
4
5
6
7

for (int i = 0; i < NUM_GAMES; i++)

{
   cout << setw(50) << left << Inventory[i].getDescription() << "$" << setw(1) << left 
     << Inventory[i].getCost() << "X" << setw(50) << left << Inventory[i].getYearReleased() << endl;
}


I have a feeling my numbers after setw(this part) are whack, but I just keep putting values into it until I get the text where I want them. So far the game titles are where they should be to the left, but the price / year part is off.

My other issue is that it's all spaced out.

Screenshot of console. http://i.imgur.com/WOvXcD0.png

Any help?
- Thank you.
Last edited on
setw sets the width of the next output operation. If you do setw(50) and then output something that is 24 characters long 26 extra spaces will be outputted to fill up all the 50 characters.

So if you want the description column to be 50 characters wide you can use setw(50) before outputting Inventory[i].getDescription() just like you do in the code above. Note that this will push the other columns to the right, so if you want the prices to be more to the left you will have to decrease the width of the description column.

Also note that the width of the command prompt is usually 80 characters so if you want everything to be on the same line you have to keep the sum of all column widths below that number. In your screenshot the year starts at position 150 (50 + 100) which is more than 80 so it is outputted on the next line.
Thank you! That was helpful and helped me better understand the use of setw. I've gotten the alignment to where I wanted it.
Topic archived. No new replies allowed.