Search code examples
c++printftext-alignment

Making a table with printf in c++


I'm trying to make a table like this.... (Just without the dots I used to separate the each item)

Weekly Payroll:

Name.....................Title.......Gross......Tax......Net

Ebenezer Scrooge Partner 250.00 ..62.25 .187.75

Bob Cratchit ..........Clerk ......15.00 ....2.00 ..13.00

This is what my code looks like for this part....

for (int count=0; count < numberOfEmployees; count++)
{
    cout << "Employee: \n";
    cout << "\t Name: ";
    cin.getline (employees[count].name, EMPLOYEESIZE); 

    cout << "\t Title: ";
    cin.getline (employees[count].title, EMPLOYEESIZE);

    cout << "\t SSNum: ";
    cin >> employees[count].SSNum;

    cout << "\t Salary: ";
    cin >> employees[count].Salary;

    cout << "\t Withholding Exemptions: ";
    cin >> employees[count].Withholding_Exemptions; 
    cin.ignore();

    cout << "\n";
}


double gross;
double tax;
double net;
double adjusted_income;

cout << "\n";

cout << "Weekly Payroll: \nName \t \t Title \t Gross \t Tax \t Net \n";


for (int count=0; count < numberOfEmployees; count++)
{
    gross = employees[count].Salary;
    adjusted_income = subtraction_times (employees[count].Salary, employees[count].Withholding_Exemptions);
    tax = adjusted_income * .25;
    net = subtraction (gross, tax);

    printf ("\n%s", employees[count].name); 
}

I have the first part of the table(the name part), but after that I dont know now to do the rest of the table. Can anyone help me?

Thanks


Solution

  • You can use printf with left-justify flag (-).

    printf("%-10s", "title"); // this will left-align "title" in space of 10 characters
    

    Here is a sample program:

    #include <string>
    using namespace std;
    
    int main()
    {
        string name = "Bob Cratchit";
        string title = "Clerk";
        float gross = 15;
        float tax = 2;
        float net = 13;
    
        printf("%-25s%-20s%-10s%-10s%-10s\n", "Name", "Title", "Gross", "Tax", "Net"); 
        printf("%-25s%-20s%-10.2f%-10.2f%-10.2f\n", name.c_str(), title.c_str(), gross, tax, net); 
        return 0;
    }
    

    Output:

    Name                     Title               Gross     Tax       Net
    Bob Cratchit             Clerk               15.00     2.00      13.00