user40120
user40120

Reputation: 648

Formatting to the Console, C++

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...

Upvotes: 1

Views: 417

Answers (1)

Michael Burr
Michael Burr

Reputation: 340466

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.

Upvotes: 3

Related Questions