Multi-line text output via printf() et al.
mail at ozzmosis.com
Thu May 14 21:02:43 UTC 2020
On 2020-05-14 22:09:04, Polytropon (freebsd at edvax.de) wrote:
> c) multiple lines in one string:
> printf("This is the first line of text.\n
> And this is the second line.\n
> Finally a third line.\n");
You need to add a line continuation backslash for this to work:
printf("This is the first line of text.\n \
And this is the second line.\n \
Finally a third line.\n");
> There is a specific restriction that if a string contains
> conversion specifications for variables, those have to be
> in the 1st argument, so printf() does not print several
> strings as individual arguments except there's a first
> one containing appropriate %s entries. This applies for
> any string containing %<something>: it has to be in the
> first argument passed to printf().
> d) multiple strings with format string:
> "This is the first line of text.\n",
> "And this is the second line.\n",
> "Finally a third line.\n");
There is the risk your program will crash here if you supply the wrong number
of arguments to printf(). It's easy to mess this up if you're not paying
attention to the parameter count, and if the printf() happens to be an error
message then the bug might not show up in production. Though linters built
into modern versions of gcc and clang will usually catch problems like this
and emit a warning.
> In this case, the \n could be in the format string instead
> of the text lines.
> So, what's the correct (or at least recommended way) of
> doing this? Think about use cases like fprintf(stderr, ...)
> for things like usage messages, or printing to a file for
> multi-line entries.
I don't think it matters too much as long as you're consistent.
String internationalisation and localisation can complicate things though.
"This " "is " "a " "string.\n"
is uncommon in C code I suspect because not many people know it's allowed
by the preprocessor. In many (most?) other languages you need to
explicitly concat the strings together.
More information about the freebsd-questions