2

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.

5
  • 1
    start by reading the man page. Commented Oct 20, 2020 at 6:59
  • Could you provide at least two example tuples of input to be formatted? This would help explaining the behavior of the different formats. Furthermore: is your question only about %-21s or you are asking also info about %3d and %12.1f? Commented Oct 20, 2020 at 7:28
  • I think my 3 strings need to align under the following line: printf("Patient Name Age Bp Warning Level\n\n" Commented Oct 20, 2020 at 7:34
  • @dot-combubble so include this info in the question. Do you have to "play" with the format string "%-21s%3d%12.1f\n" changing numbers and adding spaces in order to meet that requirement? Commented Oct 20, 2020 at 7:55
  • Yes, I need to adjust numbers to fit the spacing on my statement on top, but no spaces. Ok, I will update my question. Commented Oct 20, 2020 at 9:16

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.