Formatting Output in C++

formatting output 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++) {
putchar('-');
}
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

Formatting spacing with the printf function C

You can use extra modifiers in your format string to make printf() align things correctly:

  • To print something of a particular width prepend the the width as an integer before the formatting character: e.g., %10s will print a string to a (maximum) column of width 10, padding to the left with spaces. If your string is longer than 10 characters, it prints the full string though so bear this in mind. So your particular example:
char Months[][MAX_LEN] = {"Jan",       "Feb",     "March",    "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};

for (int i = 0; i < 12; i++) {
/* Note the 10 here! */
printf("%10s: %d\n", Months[i], Numbers[i]);
}

Results in

       Jan: 3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8

If you want to left-justify your strings, you simple prepend a - before the integer value, i.e.:

printf("%-10s: %d\n", Months[i], Numbers[i]);

Which produces

Jan       : 3
Feb : 4
March : 5
April : 1
May : 2
June : 7
July : 8
August : 9
September : 3
October : 4
November : 7
December : 8
  • Alternatively you can also use the * which allows you to state the length to pad to variably in the printf() call. To use it you calculate the length you wish to pad to as an extra argument:
int myPadWidth = 15;
/* calculate the length of Months[i] each loop and cast size_t result to int */
int lenMonths = (int)strlen(Months[i]);
/* Note the extra argument in the printf call here! */
printf("%s: %*d\n",Months[i],myPadWidth-lenMonths,Numbers[i]);

Which would result in

Jan:            3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8

How can I format a dynamic output to create a table in a printf

You can specify how many characters should be used and rest would be filled with spaces, %20s would give you 20 characters for instance, or %-20s if you want padding on the right side.

#include <stdio.h>

int main() {
char *items[] = { "First", "Second one", "Third" };
char *clients[] = { "Jon Doe", "Carol Anne", "Roscoe Williams" };

printf("%-20s\t%-20s\n", "Item", "Client");

for (int i = 0; i < 3; i++)
printf("%-20s\t%-20s\n", items[i], clients[i]);
}

How to format the output to the center in C?

There's no direct way to center text. You'll have to combine several elements:

  1. Figure out how many digits you have.
  2. Calculate how many spaces you want before and after the number.
  3. Print: printf("%*s%d%*s", spaces_before, "", num, spaces_after, "");

%*s consumes two parameters - the first is the length, the second is the string to print. Here, I tell it to print an empty string of a given width, which just prints the desired number of spaces.

Formatted output using printf() adding unwanted space/lines - C Programming

char thisName[size];

After this do

memset(thisName,0,sizeof(thisName));

%s expects a null terminated string. Or after exiting the loop

thisName[size] = '\0';

Edits:

The array size should be large enough to hold a null termination for a string.

char thisName[size + 1];

How do I properly format printing row of numbers in c?

accommodate the different lengths of numbers

float values typically range from +/-1.4...e-45F to +/-3.4...e+38F, +/-0, infinity and various not-a-numbers.

"%f" prints with 6 digits after the . as so prints 0.000000 for many small float and with many uninformative digits when very large as is thus not satisfactory.

For a general printing, begin by using "%g" which adapts its output (using exponential notation for large and wee values) and truncates trailing zeros.

Use a width, which specifies the minimum characters to print.

float typical requires up to 9 significant digits to distinguish from other float. Consider a precision.

Use source concatenation to allow for only 1 definition of the desired format.

// printf("%f  %f  %f      %f\n", A[i]->x, A[i]->y, A[i]->z, A[i]->volume)

#define FMT_F "%-15.9g"
// ^ precision
// ^^ width
// ^ left justify

printf(FMT_F " " FMT_F " " FMT_F " " FMT_F "\n",
A[i]->x, A[i]->y, A[i]->z, A[i]->volume)

// Example output
4.4 5 6 132
8.7 6.5 9.5 537.225
1.40129846e-45 -3.40282347e+38 123.4 -5.88417018e-05

More advanced code would use a compiler dependent width and precision.



Related Topics



Leave a reply



Submit