I would like to print columns using printf in C. I wrote this code:
#include <stdio.h>
void printme(char *txt1, char *txt2, char *txt3)
{
printf("TXT1: %9s TXT2 %9s TXT3 %9s\n", txt1, txt2, txt3);
}
int main()
{
printme("a","bbbbbbbeeeeebbbbb","e");
printme("aaaaaaaa","bbbbbbbbbbbb","abcde");
return 0;
}
It works but I have such output:
TXT1: a TXT2 bbbbbbbeeeeebbbbb TXT3 e
TXT1: aaaaaaaa TXT2 bbbbbbbbbbbb TXT3 abcde
So the columns are not equal-width. Basicly, I would like to make it like this, that no matter how long is text in my argument, my function would ALWAYS print out a nice formatted columns. The question is: how can I do this?
By saing nice I meant that no matter how long text I pass to my printing function, it will always print out equal-width columns, for example:
I have this output that looks like this:
a cd` fg ij
a cd fg ij
a cd fg ij
ab cd fg ij
ab cd fg i j
ab cd fg ij
ab cd fg ij
ab cde fgh ij
ab cde fgh ij
I want it to look like this (no matter how long my text arguments will be):
a cd` fg ij
a cd fg ij
a cd fg ij
ab cd fg ij
ab cd fg ij
ab cd fg ij
ab cd fg ij
ab cde fgh ij
ab cde fgh ij
C printf() print columns of data Specifying fixed field widths is useful when you want to print columns of data. printf("%d %d %d\n", val1, val2, val3);
%d is print as an int %s is print as a string %f is print as floating point.
The field width can also be specified as asterisk (*) in which case an additional argument of type int is accessed to determine the field width. For example, to print an integer x in a field width determined by the value of the int variable w, you would write the D statement: printf("%*d", w, x);
Formatted Output and the printf() function. One of the common task in every program is the printing of output. We use the output to request input from a user and later display the status/result, computations etc. In C programming there are several functions for printing formatted output.
If you want the strings to be truncated if they're larger than the column width, then you can just add a precision for the string format specification:
printf("TXT1: %9.9s TXT2 %9.9s TXT3 %9.9s\n", txt1, txt2, txt3);
With that printf()
, the output of your example program looks like:
TXT1: a TXT2 bbbbbbbee TXT3 e
TXT1: aaaaaaaa TXT2 bbbbbbbbb TXT3 abcde
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With