Course contentsShow
← C
Lesson 697 of 1,21910. Input and OutputFree lesson

How scanf leaves trailing newlines

How scanf leaves trailing newlines

What you'll learn: Why scanf often leaves a "leftover" character in your input buffer that can break your next input command.

The "Sticky Note" problem

Imagine you are a waiter taking an order. A customer writes "10" on a sticky note and hands it to you. However, to finish the note, they had to press down hard with their pen, leaving a tiny, invisible ink blot right at the end. If you only pick up the "10" and leave the paper on the table, the next waiter who comes by might get confused by that leftover blot.

In C, the scanf function behaves exactly like this. When you type a number and hit Enter, you are actually sending two things to the computer's "input buffer" (a temporary waiting area for text):

  1. The digits you typed (e.g., 10).
  2. A "newline" character (\n) created by the Enter key.

The leftover character

When you use scanf("%d", &variable), the function searches the buffer, finds the number, and stops. It thinks, "I'm only here for an integer, so I'm done!" It grabs the 10 but leaves that \n sitting right there in the buffer.

This is a silent trap. If your next line of code is another scanf for a number, it usually doesn't matter because scanf skips whitespace. But if your next line is a command that reads any character (like getchar or a string input), it will see that leftover Enter key, think you've already pressed Enter for the new prompt, and skip right past it.

Seeing it in action

Look at how the buffer retains the newline after the first input:

#include <stdio.h>

int main() {
    int age;
    char grade;

    printf("Enter your age: ");
    scanf("%d", &age); // You type '25' and hit Enter. Buffer: "25\n"
    // scanf takes 25. The '\n' is still waiting in the buffer!

    printf("Enter your grade: ");
    scanf("%c", &grade); // This will FAIL. It sees the '\n' and finishes instantly.

    return 0;
}

In the code above, the program won't even let you type a grade. It sees the "leftover" Enter key from the age prompt and assumes that was your answer.

Key takeaway

scanf extracts the data it needs but ignores the final "Enter" keypress, leaving a trailing \n in the buffer that can interfere with future inputs.