Setw not displaying correctly.

This is my code for displaying an object by overloading the << operator:
1
2
3
4
5
6
ostream& operator << (ostream& out, Winery *w)
{
	// print out a winery, as specified by lab1output.txt
	out << w->getName() << setw(26) << w->getLocation() << right << setw(24) << w->getAcres() << right << setw(7) << w->getRating();
	return out;
}


My teacher gave me a text document with a correctly formatted output included. I tried to put it into the output section on here, but the formatting is off.

Essentially it should look like this:
name                      location           acres rating
----                      --------           ----- ------
Lopez Island Vineyard     San Juan Islands       7     95


Where the dashes under name,location,acres,rating line up perfectly with the column name. The name and location should be left justified so that the words line up with the first letter of name and location. The numbers for acres and rating should be right justified, printing the first number where the last letter of acres and rating is.

My current output puts the name in the correct spot, but not the location/acres/rating. I counted the number of spaces in the text document between the columns and used setw to try and line them up. This doesn't work though. After the name is displayed, the location is displayed at a location on the screen depending on how long the name is. I don't remember setw working like this at all, so what I am I doing wrong?
setw sets the width of the next output. You want to set the width to 26 BEFORE outputting the name.

1
2
out << left << setw(26) << w->getName() << setw(18) << w->getLocation() 
    << right << setw(5) << w->getAcres() << setw(7) << w->getRating();
Last edited on
Well, that gets it closer, but it still isn't correct. Between Lopez Island Vineyard and San Juan Islands there should be 1 space (there 26 spaces from n in name to the space before location). My output puts 5 spaces between Lopez Island and San Juan, which shouldn't happen with how we have setup setw, correct?
So use setw(22) instead of setw(26).
Topic archived. No new replies allowed.