1

I'm trying to format my output in the console window in four separate fields, all evenly spaced.

out << left << setw(24) << "Name" << "Location" 
<< right << setw(20) << "Acres " << "Rating" << endl;

out << left << setw(24) << "----" << "--------" 
<< right << setw(20) << "----- " << "------" << endl;

while ( current_node )
    {
        out << left << setw(24) << current_node->item.getName() // equivalent tabs dont work?
            << current_node->item.getLocation() << right << setw(20) 
            << current_node->item.getAcres()        
            << " " << current_node->item.getRating()
            << endl;

        current_node = current_node->nextByName;
    }

The code above, for some reason, doesn't space it all evenly when the setw(n) are the same values...

warren
  • 32,620
  • 21
  • 85
  • 124
user40120
  • 648
  • 5
  • 28
  • 58
  • out << left << setw(24) << "Name" << "Location" << right << setw(20) << "Acres " << "Rating" << endl; out << left << setw(24) << "----" << "--------" << right << setw(20) << "----- " << "------" << endl; while ( current_node ) { out << left << setw(24) << current_node->item.getName() // equivalent tabs dont work? << current_node->item.getLocation() << right << setw(20) << current_node->item.getAcres() << " " << current_node->item.getRating() << endl; current_node = current_node->nextByName; } – user40120 Sep 20 '09 at 06:30
  • lampshade, read this: http://stackoverflow.com/editing-help – avakar Sep 20 '09 at 06:36
  • 2
    @avakar I believe that multiline code formatting is ignored in comments. – Justin Johnson Sep 20 '09 at 06:46
  • Justin, see the question edits. – avakar Sep 20 '09 at 09:44
  • Take a look at this question: http://stackoverflow.com/questions/119098/which-i-o-library-do-you-use-in-your-c-code/ – Martin York Sep 20 '09 at 18:40

1 Answers1

3

The setw() manipulator affects only the next output field - it's not 'sticky'. So you'll need to specify what you want for each output field, not just change it once and expect it to act on each of the following output items.

I think you want something like:

cout << left << setw(24) << "Name" << setw(24) << "Location" ;
cout << right << setw(20)<< "Acres" << setw(20) << "Rating" << endl;

cout << left << setw(24) << "----" << setw(24) << "--------" ;
cout << right << setw(20) << "-----" << setw(20) << "------"  << endl;

while ( current_node )
    {
        cout << left << setw(24) << current_node->item.getName()
                     << setw(24) << current_node->item.getLocation()
             << right 
                     << setw(20) << current_node->item.getAcres()
                     << setw(20) << current_node->item.getRating()
             << endl;

        current_node = current_node->nextByName;
    }

C++ stream I/O - it's type safe, but sanity unsafe.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760