c++coutsetw

Why is the output ending the line early and filling every empty spaces with setfill instead of creating a line with it?


Im trying to create a ling of the special character "="

Output I want

Name====================
Horace Horsecollar    56.00  12.50  700.00  210.00  10  480.00
Eleven Thirty         34.00  12.50  425.00  127.50  10  287.50
Victoria Elven        34.00  12.50  425.00  127.50  10  287.50

but the output here is filling all empty spaces in the output with "="

Output I'm getting

Name
==Horace Horsecollar====56.00  12.50  700.00  210.00  10  480.00
Eleven Thirtyman======34.00  12.50  425.00  127.50  10  287.50
Victoria Elven========34.00  12.50  425.00  127.50  10  287.50

Employees.push_back(new Employee("Horace Horsecollar", 56, 12.5));
Employees.push_back(new Employee("Eleven", 34, 12.5));
Employees.push_back(new Employee("Victoria Elven", 34, 12.5));

Code

cout << "Name" << setw(20) << setfill('=') << endl;

for (vector<Employee *>::iterator i = Employees.begin(); i < Employees.end(); i++) {
  cout << (*i)->getName() 
  
  << setw(27 - ((*i)->getNamesize()) ) << fixed << setprecision(2) 
  << (*i)->getHoursWorked() 
  << "  " << (*i)->getHourlyRate() 
  << "  " << (*i)->getGrossPay()
  << "  " << (*i)->getTaxes()
  << "  " << 10
  << "  " << (*i)->getNetPay() << "\n";

I'm really really confused, there's something about cout that I don't understand, but I don't know what it is.


Solution

  • You need to put formatters before the text.

    








cout << setw(21) << setfill('=') << left << "Name" << setfill(' ') << endl;
    

    The left keyword means that the following text will be lined up on the left side of the 21-character column. The fill characters will go on the right.

    This also goes for the first part of your loop where the name is printed. The entire point of setw() is that you don't need to deal with the length of the data in the column.

    for (vector<Employee *>::iterator i = Employees.begin(); i < Employees.end(); i++) {
      cout << setw(22) << left << (*i)->getName() 
           << fixed << setprecision(2) << (*i)->getHoursWorked() 
           << "  " << (*i)->getHourlyRate()
           << "  " << (*i)->getGrossPay()
           << "  " << (*i)->getTaxes()
           << "  " << 10
           << "  " << (*i)->getNetPay() << "\n";
    }
    

    Here, the name will be put on the left side of a 22-character column. The rest of the space is taken up by spaces because of the call to setfill(' ') after the Name heading.