Nack Nack - 5 months ago 55
C Question

formatting output in C

I'm testing input formatting in C with a simple program to get familiar with C's commands, and I can't seem to figure out how to format this one output to be dynamic. So here's my problem: When you enter a name, the Salary, tax, and netpay don't adjust to the space making it look crummy. If I enter a looooong first name, it will move over on the same line and not appear under it's specified column that defines the number. Here's my code:

#include <stdio.h>

char name[20];
char *nameptr = name;
double netpay, tax, salary;

printf("Enter Name: ");
scanf("%s", nameptr);
printf("\nEnter salary: ");
scanf("%lf", &salary);

tax = (salary * 0.25);
netpay = salary - tax;

printf("\n\nName\t\tSalary\t Tax\t Netpay\n");
printf("%s", nameptr);

printf("%15.2lf - %.2lf = %.2lf\n\n",salary, tax, netpay);

I want the program to let the numbers stay where they are, and not adjust by the name length.


If they have to adjust, can I use the length of the name to adjust the

printf("\n\nName\t\tSalary\t Tax\t Netpay\n");


printf("%15.2lf - %.2lf = %.2lf\n\n",salary, tax, netpay);


Is this possible in C?


Use a variable field width * to align the output. "%*s". @Barmar
Use - to left justify. "%-*s"
Use the return value of printf() to make the "---".

What makes this approach good is that the Name_Width and Money_Width can be use to control the width of the column title and the width of the data.

  int Money_Width = 15;
  int Name_Width = strlen(nameptr);
  if (Name_Width < 4) Name_Width = 4; // "Name" width

  puts("");  // \n

  int width = printf("%-*s %*s %*s %*s\n", Name_Width, "Name", Money_Width,
      "Salary", Money_Width, "Tax", Money_Width, "Netpay");

  for (int i = 0; i < width; i++) {
  puts("");  // \n

  printf("%-*s %*.2f %*.2f %*.2f\n", Name_Width, nameptr,
      Money_Width, salary, Money_Width, tax, Money_Width, netpay);

Sample output

Enter Name: asd

Enter salary: 123

Name          Salary             Tax          Netpay
asd           123.00           30.75           92.25