Reputation: 1460
I am learning C++. I have a problem formatting the output of my program. I would like to print there columns perfectly aligned but so far I cannot do it, here is my code:
int main()
{
employee employees[5];
employees[0].setEmployee("Stone", 35.75, 053);
employees[1].setEmployee("Rubble", 12, 163);
employees[2].setEmployee("Flintstone", 15.75, 97);
employees[3].setEmployee("Pebble", 10.25, 104);
employees[4].setEmployee("Rockwall", 22.75, 15);
printEmployees(employees, 5);
return 0;
}
// print the employees in my array
void printEmployees(employee employees[], int number)
{
int i;
for (i=0; i<number; i++) {
employees[i].printEmployee();// this is the method that give me problems
}
cout << "\n";
}
in the class employee I have the print employee method:
void printEmployee() const
{
cout << fixed;
cout << surname << setw(10) << empNumber << "\t" << setw(4) << hourlyRate << "\n";
}
Problem is when I print "flinstones" line the emp number and rate are not lined up. something like this happens:
Stone 43 35.750000 Rubble 163 12.000000 Flintstone 97 15.750000 Pebble 104 10.250000 Rockwall 15 22.750000
Can anybody help me? (I tried to add tabs.. but it didn't help)
Upvotes: 10
Views: 86214
Reputation: 1
C++ supports a number of features that could be used for formatting the output. These features include:
Using ios class function, we can use width() method of ios class, like this:
Or we can use manipulators to format the output. To print the above output we can use:
cout << right << setw(5) << 543 << right << setw(5) << 12 << endl;
It will allocate 5 character width for first argument (here it is 543) and format it by padding it on the right. Similarly it will allocate a 5 character field for second argument.
Upvotes: 0
Reputation: 2115
In the class employee of print employee method: Use this line to print.
cout << setw(20) << left << surname << setw(10) << left << empNumber << setw(4) << hourlyRate << endl;
You forgot to add "<< left
". This is required if you want left aligned.
Hope it ll useful.
Upvotes: 26
Reputation: 490108
You need to set a width before you print out the name to get other things to line up after that. Something on this general order:
cout << left << setw(15) << surname
<< setw(10) << empNumber << "\t"
<< setw(4) << hourlyRate << "\n";
I'd (at least normally) avoid trying to mix fixed-width fields with tabs as well. It's generally easier to just use widths to align things.
Upvotes: 9