Coding

How to Print in C: printf, puts and putchar Explained

To print in C, include <stdio.h> and call printf("Hello, world\n"); for formatted output, puts("Hello, world"); for a string followed by a newline, or putchar('A'); for a single character. All three write to standard output (stdout), which is normally your terminal.

#include <stdio.h>

int main(void) {
    printf("Hello, %s! You have %d new messages.\n", "Ada", 3);
    puts("This line ends with a newline automatically.");
    putchar('Z');
    putchar('\n');
    return 0;
}

Example output:

Hello, Ada! You have 3 new messages.
This line ends with a newline automatically.
Z

Which function should you use to print in C?

The standard library gives you several ways to write text. Pick by what you are printing:

FunctionPrintsAdds newline?Returns on success
printf(format, ...)Formatted text with values insertedNoNumber of characters written
puts(str)A null-terminated stringYesA non-negative value (implementation-defined)
putchar(ch)One characterNoThe character written
fputs(str, stream)A string to any streamNoA non-negative value (implementation-defined)
fprintf(stream, format, ...)Formatted text to any streamNoNumber of characters written

On failure, puts, fputs and putchar return EOF and set the error indicator on the stream. printf returns a negative value if an output or encoding error occurred.

How to print with printf

printf is the general-purpose choice. The first argument is a format string. Every % code in it is replaced by the next argument, converted to text. The reference page on cppreference states that printf writes to stdout, while fprintf writes to a stream you name.

int age = 30;
double height = 1.82;
char initial = 'K';
const char *city = "Vilnius";

printf("Age: %d\n", age);
printf("Height: %.2f m\n", height);
printf("Initial: %c\n", initial);
printf("City: %s\n", city);

Example output:

Age: 30
Height: 1.82 m
Initial: K
City: Vilnius

The code after % must match the type of its argument: %d for int, %f for double, %c for a character, %s for a string. The full list, including width, precision and size_t with %zu, is in Format Specifiers in C: printf and scanf Reference.

Printing a percent sign, quotes and backslashes

A lone % in a format string starts a conversion, so write %% to print a percent sign. Inside a string literal, a double quote is \" and a backslash is \\.

printf("Progress: 75%%\n");
printf("She said \"hi\"\n");
printf("Path: C:\\work\\notes.txt\n");

Example output:

Progress: 75%
She said "hi"
Path: C:\work\notes.txt

What printf returns

On success printf returns the number of characters it sent to the output. Most programs ignore this, but it is handy when you want to align text or detect a failed write.

int written = printf("Total: %d\n", 250);
printf("That line was %d characters long.\n", written);

Example output:

Total: 250
That line was 11 characters long.

The count includes the newline: Total: 250 is 10 characters plus \n.

How to print a line of text with puts

puts writes the characters of a string and then one extra newline. It does not write the terminating null character. If all you want is a line of fixed text, it is simpler than printf because you do not need \n and you cannot trip over a stray %.

puts("Starting backup");
puts("Done");

Example output:

Starting backup
Done

The success return value of puts is not portable. cppreference notes that some implementations return the last character written, some return the number of characters written, and some return a constant. Only compare the result with EOF to detect failure:

if (puts("Starting backup") == EOF) {
    perror("puts");
}

A typical cause of failure, according to cppreference, is running out of space on the file system when stdout is redirected to a file.

puts versus fputs

The two differ in one way that surprises people. puts appends a newline. fputs does not, and it takes a stream argument. To print a string with no newline to the terminal, use fputs("text", stdout).

fputs("Loading", stdout);
fputs("...", stdout);
puts(" done");

Example output: Loading... done

How to print one character with putchar

putchar writes a single character to stdout. Its argument is an int that is converted to unsigned char before it is written, and it is equivalent to putc(ch, stdout). It returns the character written, or EOF on failure.

for (char letter = 'a'; letter <= 'e'; letter++) {
    putchar(letter);
}
putchar('\n');

Example output: abcde

Because of the conversion, the value you get back is not always the value you passed. The cppreference page shows that passing 0x1070 writes only the low byte, 0x70, which is the letter p. For ordinary character values this never matters.

Use putchar when you generate output one character at a time, such as printing a row of dashes or converting text as you go. For anything longer than a few characters, puts or printf is clearer.

Why output sometimes does not appear: flush stdout

Text sent to stdout can wait in a buffer instead of reaching the screen immediately. fflush(stdout) writes any unwritten data from the buffer to the output device. The classic case is a prompt without a newline, followed by reading input:

char name[64];

printf("Enter your name: ");
fflush(stdout);

if (fgets(name, sizeof name, stdin) != NULL) {
    printf("Hello, %s", name);
}

Without the fflush call, the prompt may not show up before the program waits for input on some systems. The call is harmless when the text would have appeared anyway. fflush returns zero on success and EOF on failure. For reading input, see scanf in C: Syntax, Return Value and Pitfalls.

Common mistakes when printing in C

  • Forgetting the header. Without #include <stdio.h>, the compiler does not know printf and puts. Add the include at the top of the file.
  • Forgetting \n. printf("Hello") leaves the cursor on the same line, so the next output, or your shell prompt, runs straight after it. End lines with \n, or use puts.
  • A specifier that does not match the argument. printf("%d\n", 3.5) is undefined behavior. cppreference says the same for a mismatched type and for fewer arguments than the format needs. Extra arguments are evaluated and ignored.
  • Printing a string with single quotes. 'A' is a character, "A" is a string. putchar("A") is a type error, and printf("%s", 'A') is undefined behavior.
  • Passing user text as the format string. printf(text) treats any % in text as a conversion. Use printf("%s", text) or puts(text).
  • Printing a pointer value with %d. To print a memory address, use %p and cast the pointer to void *. Pointers themselves are covered in Pointers in C Explained with Examples.

Printing to a file or to the error stream

The same functions have versions that take a stream. fprintf(stderr, ...) writes to standard error, which keeps diagnostics out of output that is redirected to a file. fprintf(fp, ...) and fputs(text, fp) write to a file opened with fopen.

fprintf(stderr, "Error: could not open %s\n", "config.txt");

To build a string in memory instead of printing it, snprintf(buffer, size, format, ...) writes into a character array and never writes more than size bytes, including the terminating null.

Frequently asked questions

What is the difference between printf and puts in C?
printf takes a format string and extra arguments, so it can print numbers, characters and strings in one call, and it adds no newline on its own. puts takes only a null-terminated string and always writes a newline after it. Use puts for a plain line of text and printf when you need to insert values.
How do I print a new line in C?
Put \n at the end of the string, as in printf("Hello\n"). puts adds the newline for you. Without it, the next output continues on the same line.
Why does printf not show output before my program waits for input?
Output to stdout can sit in a buffer until it is flushed. Call fflush(stdout) after printing a prompt that has no trailing newline, so the text appears before the program reads input.
How do I print a variable in C?
Use printf with a format specifier that matches the variable's type, for example printf("%d", count) for an int or printf("%f", price) for a double. A specifier that does not match the argument type is undefined behavior.
Do I need to include a header to print in C?
Yes. Add #include <stdio.h> at the top of the file. It declares printf, puts, putchar, fputs and the stdout stream.

Sources