Cleaning up output text in proper columns

I was wondering how to square up columns so my output looks cleaner instead of it being jumbled like it kind of it now due to the different legnth of names.

.txt file:
Johnson 60 12.50
Aniston 65 13.25
Cooper 50 14.50
Gupta 70 14.75
Blair 55 10.50
Clark 40 18.75
Kennedy 45 20.50
Bronson 60 20.00
Sunny 65 18.75
Smith 30 9.75


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int main()
{
	read_data();
	double average, sal_sum = 0;

	cout << setw(4) << "Name" << setw(16) << "Hrs Worked" << setw(10) << "Pay Rate";
        cout << setw(10) << "Salary\n";
	cout << "------------------------------------------\n";

	for (int i = 0; i < 10; i++)
	{
		info[i][2] = salary(info[i][0], info[i][1]);
		sal_sum += info[i][2];
		cout << name[i] << ' ' << fixed << setprecision(2) << setw(9) << info[i][0] << ' ';
		cout << setw(11) << info[i][1] << ' ' << setw(11) << info[i][2] << endl;
	}
	cout << fixed << setprecision(2) << sal_sum << endl;

	average = sal_sum / 10.0;

	cout << "Average Salary: $" << average << endl;

	for (int i = 0; i < 10; i++)
	{
		if (info[i][2] > average)
			cout << name[i] << ' ';
	}
	return 0;
}
Last edited on
if someone would be able to inform me on how to upload a .txt file to this post as well... that would be sweet

Similar to adding code tags. Instead of using the <> button from the toolbar on the selected text, use the button to the right of it. It has a tooltip 'Program output'
I didn't run your code, but if you just want the names to be padded so that the numbers all start together, you can do something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Example program
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>

struct Employee {
    std::string name;
    double hours_worked;
    double pay_rate;
};

int main()
{
    std::vector<Employee> employees {
        {"Johnson", 60, 12.50},
        {"Aniston", 65, 13.25},
        {"Cooper", 50, 14.50},
        {"Bronson", 60, 20.00},
        {"Sunny", 65, 18.75},
        {"Smith", 30, 9.75}
    };

    for (const auto& employee : employees)
    {
        std::cout << std::setw(10) << std::left << employee.name  << ' '
                  << employee.hours_worked << ' ' << employee.pay_rate << '\n';   
    }
}
Last edited on
For something of variable width, I tend to prefer a first pass to calculate the minimum width required and then format.

1
2
3
4
5
6
7
8
9
10
    int min_width = 0;
    for (const auto& employee : employees)
    {
        min_width = std::max( min_width, employee.name.size() );
    }

    for (const auto& employee : employees)
    {
        std::cout << std::setw(min_width) << ...
    }
Simply, L14 you need setw() for name[i] like you have for the other fields. You may also want left as well to left align.
Topic archived. No new replies allowed.