CodeBlanks Logo Icon CodeBlanks

puts and fputs

Learn to print strings with puts and fputs.

Printing strings with puts

puts(str) prints a string to the screen and automatically adds a new line at the end. It's simpler than printf; a good choice when you only need to print fixed text.

puts("Hello world!");
puts("Welcome");

The output is two lines: each puts call adds \n at the end. Compared to printf, printf("Text\n") and puts("Text") give the same result. On error it returns EOF.

fputs and streams

fputs(str, stdout) writes a string to a given stream. stdout is standard output; stderr is the error output. Unlike puts, fputs does not add a new line automatically.

fputs("An error occurred\n", stderr);
fputs("OK\n", stdout);

Writing errors to stderr is a good habit; it keeps them separate from normal output. stdout and stderr go to the same place in most terminals, but can be split with redirection.

Practice Print with puts and fputs

Write a C program. Print one string with puts("Hello world!");. Print a second string with fputs("Welcome\n", stdout);. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Print two strings with puts and fputs
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    puts("Hello world!");
    fputs("Welcome\n", stdout);
    return 0;
}

Expected output

Hello world!
Welcome

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the puts call

Question
____("Hello world!");
Answer
puts("Hello world!");

Explanation: puts prints the string and adds a new line.

2 Match the output functions

Term Meaning
puts String + new line
fputs String to a stream
stdout Standard output
stderr Error output

3 What's the difference between puts and fputs?

main.c
puts("A");
fputs("A", stdout);
  • They are identical
  • fputs adds a new line, puts does not
  • puts adds a new line, fputs does not Correct answer
  • puts only prints numbers

Explanation: The main difference is the new line behavior; puts adds, fputs does not.

All lessons in Beginner