dima

on software
Posts from blog by tag scanf:

The Pitfalls of Reading User Input in C: a Story About scanf and Stdin

I recently had to write a piece of C code that takes some input from stdin, ignores the newline, discards whatever exceeds the buffer, and does this repeatedly in a loop.

Knowing something about scanf syntax (man) I came up with this:

#include <stdio.h>

void take_input(void)
{
    char buf[20];
    printf("> ");
    scanf("%19[^\n]", buf);
    printf("input=`%s`\n", buf);
}

int main(void)
{
    for (int i = 0; i < 5; i++) {
        take_input();
    }

    return 0;
}

(Note: The original code used an infinite loop, but a simple for is enough to demonstrate the behavior.)

When I ran it, the result was surprising:

$ gcc -o main main.c
$ ./main
> hello world↵
input=`hello world`
> input=`hello world`
> input=`hello world`
> input=`hello world`
> input=`hello world`
$ █

It consumed the string once and printed the same value 5 times. Why?

Read more