Nearby lessons
67 of 124C - String Output
Printing strings in C — printf with %s, the width and precision modifiers that align text into columns, plus puts and fputs and when each is the better choice.
printf with %s
The %s specifier prints characters starting at the given address and stops at the first '\0'. Nothing is added — you supply the newline yourself:
puts() — Simple and Adds a Newline
puts takes exactly one string and always appends '\n'. It cannot format, but for a plain message it is shorter and slightly faster:
fputs() — No Automatic Newline
fputs writes to a stream and does not add a newline. It is the counterpart to fgets:
Choosing Between Them
printf("%s") | puts() | fputs() | |
|---|---|---|---|
| Adds newline | No | Yes | No |
| Formatting | Full | None | None |
| Multiple values | Yes | No | No |
| Choose the stream | Via fprintf | No — always stdout | Yes |
| Best for | Mixed or aligned output | A plain line of text | Files and stderr |
puts for a whole line of fixed text, printf whenever you need to combine values or control alignment, and fputs when writing to a file or to stderr.Width — Building Columns
A number between % and s sets a minimum field width. A minus sign left-aligns; without it, text is right-aligned:
A Formatted Table
Width modifiers are how you produce aligned reports without any external library:
Precision — Truncating Output
%.Ns prints at most N characters. Unlike width, precision does cut text short — handy for previews:
Width from a Variable
* takes the width from an argument, so column sizes can be computed at runtime:
Printing Character by Character
Sometimes you need per-character control — to reverse text, add spacing, or handle an array with no terminator:
Common Mistakes
- Using
%sfor a single character —printf("%s", 'A')treats 65 as an address and crashes. Use%c. - Using
%cfor a string — prints one meaningless character. - Passing user text as the format string —
printf(userInput)is a format-string vulnerability. Writeprintf("%s", userInput). - Expecting width to truncate —
%3snever shortens text; only%.3sdoes. - Printing a string with no
\0—%sruns past the end into garbage.
printf(variable). If the text contains a %s or %n, printf will read arguments that were never passed — a real and long-exploited security hole. Always pass the value through a literal format: printf("%s", variable).- printf("%s", s) prints until the \0 — no newline added.
- puts(s) prints the string and adds a newline automatically.
- fputs(s, stdout) prints without adding a newline.
- %-20s left-aligns in 20 columns; %20s right-aligns.
- %.5s truncates output to the first 5 characters.