Reputation: 45
In one of the assignments we have a code like fprintf(output, "%-21s%3d%12.1f\n", name, age, temperature);
These numbers -21, 3 and 12 are supposed to help us align or format the text on the lower row compared to the upper one (I guess this is considered a better option than trying to space out strings with spaces). I don't understand what -21 means or how I should be using these numbers to align the text the way I want. I think my 3 strings need to align under the following line: printf("Patient Name Age Bp Warning Level\n\n"
Please note: I have to use only this option to align the text.
Upvotes: 2
Views: 132
Reputation: 3256
The numbers 21, 3, and 12 are field width specifiers. For instance 21 means that if the value is narrower than 21 chars, it is padded with spaces. The -
is a modifier to say that padding should left align (by padding spaces on the right end), rather than the default right aligning behavior.
Reference: https://linux.die.net/man/3/fprintf
Upvotes: 1
Reputation: 5389
A number before format specifier is a field width. It is an optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the negative value has been given).
So, in your case name
will be left aligned in field with width of 21 symbol. age
, and temperature
will occupy at least 3 and 12 symbols filled with spaces on the left if needed.
Upvotes: 1