scanf in C: Read User Input

A C program that asks for an age and a city needs to read the values typed at the keyboard. scanf() reads input from the standard input stream and converts it into values your program can store in variables.

I’ll show how to match each conversion to its destination variable and check how many values scanf() assigned.

TL;DR: scanf reads formatted input

scanf() reads from standard input, matches characters against a format string, and stores converted values through the pointers you pass.

  • Include stdio.h and match each conversion specifier to a pointer of the right type.
  • Check the return value against the number of values you expected.
  • Give %s a field width, and use fgets() when the input should include spaces.

What is scanf in C?

scanf() is a formatted-input function in stdio.h. It reads stdin, usually keyboard input, and uses a format string to match and convert characters.

Each conversion needs a pointer to writable storage. Pass &age for an int. A character array name already points to its first element.

scanf() returns the number of items matched and assigned, in conversion order. Check that count before using the values. It counts assignments, not characters consumed.

SpecifierReadsArgument example
%dDecimal int&age
%ffloat&temperature
%lfdouble&distance
%cOne character&initial
%sNon-whitespace tokencity

The destination must match the conversion. %f expects a float pointer, while %lf expects a double pointer. Choose a specifier from the destination variable’s type, then pass its address in the same argument position.

How to use scanf to read user input

Use one conversion for each value and pass destination addresses in the same order. This example reads an integer and a bounded word, then checks both assignments.

Step 1: Match conversions to destination variables

The width limits input to 19 characters. Since city holds 20 bytes, one byte remains for the terminating null character. Without a width, a longer token can overrun the array.

#include <stdio.h>

int main(void) {
    int age;
    char city[20];
    int converted;

    converted = scanf("%d %19s", &age, city);
    if (converted != 2) {
        puts("Input did not match: enter an integer and one word.");
        return 1;
    }

    printf("Read %d values: age=%d, city=%s\n", converted, age, city);
    return 0;
}

I used %19s because city has 20 bytes, leaving room for its null character. The receipt records the successful two-field run.

Step 2: Compile and check the result

Compile the file, then provide an integer and one city token. This command is the captured run.

gcc -std=c11 -Wall -Wextra -pedantic scanf_demo.c -o scanf_demo && printf "27 Pune\n" | ./scanf_demo
Terminal output after scanf reads an age and city token

The captured output is:

Read 2 values: age=27, city=Pune

The program assigned two values, so both are safe to print. If conversion stops early, the check prevents use of an unassigned value.

A successful conversion does not validate a range. Check allowed ages or quantities separately.

Common errors with scanf

A failed match leaves the unmatched input in the stream, so a later read can fail again. Check the assignment count and use line input when you need spaces or recovery.

Input caseBehaviorPractical response
Text where %d expects a numberConversion fails and that field is not assignedCheck the return count before using the variable
End of input before the first assignmentscanf() returns EOFHandle EOF as an input-ending condition
%s with a space in the inputReads only the token before whitespaceUse fgets() for a whole line
%c after a numberCan read the whitespace left after the numberUse a leading space in the format, as in ” %c”, to skip whitespace

Whitespace in the format skips input whitespace. The space between %d and %s accepts spaces, tabs, or newlines, but %c reads the next character as-is. Use a leading space in ” %c” to skip whitespace first.

After a failed conversion, the unmatched character remains for the next read. Repeating scanf() without consuming it can fail again, so line input is simpler when the program must explain an error and retry.

Use fgets() to read a bounded line, then sscanf() to parse it. This gives the program a full line to inspect before retrying.

fscanf() reads from a file stream. The Linux scanf manual recommends whole-line input when recovery and precise handling matter.

Conclusion: check each conversion

scanf() is useful when the input format is known and each destination matches its conversion. Pass the right pointers, bound string reads, and use the return count before relying on the values.

FAQ

These answers cover two common details about scanf input.

What does scanf() return in C?

It returns the number of input items successfully matched and assigned. It returns EOF when input ends or an error occurs before the first assignment.

Can scanf() read spaces in a string?

The %s conversion stops at whitespace. Use fgets() to read a bounded line that can contain spaces.

Ninad Pathak
Ninad Pathak

Ninad Pathak is a founding member and Editor in Chief at CodeForGeek. He writes about practical AI tooling and developer workflows, and outside work you will likely find him with a book, hot brewed coffee, and ambient music.

Articles: 80