Nearby lessons

67 of 124

C - 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:

Example01
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[] = "Rahul";
6 char city[] = "Delhi";
7 
8 printf("%s\n", name);
9 printf("%s lives in %s\n", name, city);
10 printf("No newline here...");
11 printf("so this continues on the same line\n");
12 return 0;
13}
Output
Rahul
Rahul lives in Delhi
No newline here...so this continues on the same line

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:

Example02
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char msg[] = "Hello, World!";
6 
7 puts(msg); /* newline added automatically */
8 puts("Second line");
9 printf("%s\n", msg); /* the printf equivalent */
10 return 0;
11}
Output
Hello, World!
Second line
Hello, World!

fputs() — No Automatic Newline

fputs writes to a stream and does not add a newline. It is the counterpart to fgets:

Example03
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 fputs("No", stdout);
6 fputs(" newline", stdout);
7 fputs(" added\n", stdout); /* supplied manually */
8 
9 fputs("This goes to stderr\n", stderr);
10 return 0;
11}
Output
No newline added
This goes to stderr

Choosing Between Them

printf("%s")puts()fputs()
Adds newlineNoYesNo
FormattingFullNoneNone
Multiple valuesYesNoNo
Choose the streamVia fprintfNo — always stdoutYes
Best forMixed or aligned outputA plain line of textFiles and stderr
In simple words: use 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:

Example05
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 printf("|%10s|\n", "Hi"); /* right-aligned in 10 */
6 printf("|%-10s|\n", "Hi"); /* left-aligned in 10 */
7 printf("|%3s|\n", "TooLong"); /* width is a MINIMUM, never truncates */
8 return 0;
9}
Output
|        Hi|
|Hi        |
|TooLong|

A Formatted Table

Width modifiers are how you produce aligned reports without any external library:

Example06
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char names[3][20] = {"Rahul", "Priyanka", "Amit"};
6 char cities[3][20] = {"Delhi", "Mumbai", "Chennai"};
7 int ages[3] = {25, 30, 28};
8 int i;
9 
10 printf("%-12s %-12s %5s\n", "NAME", "CITY", "AGE");
11 printf("-----------------------------------\n");
12 for (i = 0; i < 3; i++)
13 printf("%-12s %-12s %5d\n", names[i], cities[i], ages[i]);
14 return 0;
15}
Output
NAME         CITY           AGE
-----------------------------------
Rahul        Delhi           25
Priyanka     Mumbai          30
Amit         Chennai         28

Precision — Truncating Output

%.Ns prints at most N characters. Unlike width, precision does cut text short — handy for previews:

Example07
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char text[] = "Programming";
6 
7 printf("Full : %s\n", text);
8 printf("First 4 : %.4s\n", text);
9 printf("First 7 : %.7s\n", text);
10 printf("Padded : |%-15.6s|\n", text); /* truncate then pad */
11 return 0;
12}
Output
Full     : Programming
First 4  : Prog
First 7  : Program
Padded   : |Progra         |

Width from a Variable

* takes the width from an argument, so column sizes can be computed at runtime:

Example08
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4int main()
5{
6 char names[3][20] = {"Al", "Bernadette", "Chen"};
7 int i, width = 0;
8 
9 for (i = 0; i < 3; i++) /* find the longest */
10 if ((int) strlen(names[i]) > width)
11 width = strlen(names[i]);
12 
13 for (i = 0; i < 3; i++)
14 printf("|%-*s|\n", width, names[i]); /* width supplied by * */
15 return 0;
16}
Output
|Al        |
|Bernadette|
|Chen      |

Printing Character by Character

Sometimes you need per-character control — to reverse text, add spacing, or handle an array with no terminator:

Example09
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4int main()
5{
6 char s[] = "Hello";
7 int i, len = strlen(s);
8 
9 printf("Spaced : ");
10 for (i = 0; i < len; i++) printf("%c ", s[i]);
11 
12 printf("\nReversed: ");
13 for (i = len - 1; i >= 0; i--) putchar(s[i]);
14 
15 printf("\nWith %%c : ");
16 for (i = 0; s[i] != '\0'; i++) printf("%c", s[i]);
17 printf("\n");
18 return 0;
19}
Output
Spaced  : H e l l o
Reversed: olleH
With %c : Hello

Common Mistakes

  • Using %s for a single characterprintf("%s", 'A') treats 65 as an address and crashes. Use %c.
  • Using %c for a string — prints one meaningless character.
  • Passing user text as the format stringprintf(userInput) is a format-string vulnerability. Write printf("%s", userInput).
  • Expecting width to truncate%3s never shortens text; only %.3s does.
  • Printing a string with no \0%s runs past the end into garbage.
Never write 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).
📝 Key Takeaways
  • 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.

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4