Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 135 ยท Getting Started

Reading Input with scanf and fgets

Read user input in C safely - scanf and its return value, the leftover newline trap, fgets with sscanf or strtol, getchar, and reading until EOF.

Programs become interesting when they react to data you give them. In C, a program reads text from standard input (stdin): the keyboard when you run it in a terminal, a file when input is redirected, or, in our editors, the Input box under the code. Whatever you type there is fed to the program when you press Run, one line per line of the box.

C gives you several ways to read that text. scanf is the quickest to write but has traps that catch every beginner. fgets reads a whole line safely, and combined with sscanf or strtol it's the pattern professionals use. This lesson covers both approaches, getchar for single characters, and how to read until the input runs out.

scanf: reading formatted input

scanf is the mirror image of printf: it takes a format string and reads values that match it. The important difference is that scanf needs to know where to store each value, so you pass the address of each variable with the & operator:

C Reading numbers with scanf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The Input box contains 28 and 1.75 on separate lines. scanf("%d", &age) skips any leading whitespace, reads digits and stores the number in age. Then %lf reads a double into height.

The prompts and the results appear on the same line in the output, because the input you typed isn't echoed back: the program only sees it, it doesn't print it.

Two rules to remember:

  • Pass addresses. scanf("%d", age) (without &) passes the variable's value instead of its location; GCC warns and the program will likely crash. You'll understand & fully in Pointers.
  • %lf for double in scanf. With printf, %f works for both float and double. With scanf, %f means float and %lf means double, because scanf writes to the variable and must know its exact size.
Type scanf specifier
int %d
unsigned int %u
long, long long %ld, %lld
float %f
double %lf
char %c (or " %c" to skip whitespace)
a word into char buf[20] %19s

Several values at once

Every numeric specifier skips leading whitespace, including spaces, tabs and newlines. That means the values can be on one line or many:

C Several values in one call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints scanf read 3 values and Total: 12.55. Try putting each number on its own line: the result is the same. Now type 3 abc 7 in the Input box and run again. This time the program prints scanf read 1 values and no total.

Always check scanf's return value

scanf returns how many values it successfully stored. It stops at the first input that doesn't match the format, and it returns EOF (a negative constant) if the input ended before it could read anything. An unchecked scanf that fails leaves your variable uninitialized, and reading an uninitialized variable is a bug that can print anything.

C Detecting bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With twelve in the Input box, scanf can't read a number, returns 0, and the program reports the problem and exits with status 1. Replace the input with 12 and it works.

There's a subtle catch: a failed scanf leaves the bad text in the input. If you simply call scanf("%d", ...) again, it meets the same twelve and fails again, forever. That's one of the reasons the fgets pattern below is better for interactive programs.

Warning: scanf("%d", &n) also accepts input like 42abc (it reads 42 and leaves abc behind) and silently overflows on huge numbers like 99999999999. Fine for quick experiments, risky for real programs.

The leftover newline

When you type 5 and press Enter, the input contains two characters: 5 and a newline \n. scanf("%d", ...) reads the 5 and leaves the \n waiting. Numeric specifiers skip it next time, but %c reads any character, including that newline:

C The leftover newline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first %c gets the newline (character code 10). Putting a space before %c in the format tells scanf to skip any whitespace first, so the second call reads y. The same trap appears when you mix scanf with fgets: fgets sees the leftover newline as an empty line.

Reading words with %s

%s reads one word: it skips whitespace, then reads characters until the next space or newline. The text goes into a char array, which you'll study in Strings. Arrays already act like addresses here, so there's no &:

C
char city[20];
scanf("%19s", city);   /* at most 19 characters + the terminating '\0' */

The width 19 is essential. A plain %s keeps writing as long as the input continues, past the end of the array, overwriting other memory. That's a buffer overflow, one of the most common security bugs in C history. Always give %s a width of one less than the array size. And remember that %s stops at a space, so it can't read New York in one go.

fgets: reading a whole line safely

fgets reads an entire line, spaces included, into a character array and never writes past its end:

C
char *fgets(char *buffer, int size, FILE *stream);

It reads until it has stored a newline, reached size - 1 characters, or hit the end of the input. It always adds the terminating '\0', and it returns NULL if nothing could be read. Unlike scanf, it keeps the newline in the buffer, so you usually remove it:

C Reading full lines with fgets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

strcspn(name, "\n") returns the position of the first newline (or the end of the string if there is none), and writing '\0' there shortens the string. sizeof name gives the array size (50), so the limit always matches the buffer, even if you change its size later.

Warning: You may find gets(buffer) in old code. It reads a line with no size limit, so it can't be used safely, and C11 removed it from the language. Use fgets instead.

fgets + sscanf or strtol: the safe pattern

The robust way to read a number is to read the whole line with fgets first, then convert the text. Bad input can never get stuck, because the whole line has already been consumed:

  • sscanf(line, "%d", &n) works like scanf but reads from a string.
  • strtol(line, &end, 10) converts text to a long and tells you exactly where the number ended, so you can reject 42abc. It sets errno to ERANGE when the number is too big.
C Validating numbers with strtol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The Input box holds four attempts. The program rejects abc (no digits), 42abc (junk after the number) and the 20-digit number (out of range for long), then accepts 17 and prints got 17, doubled: 34. This loop is the shape of every "keep asking until the input is valid" prompt. Converting Strings and Numbers covers strtol, strtod and sscanf in depth.

getchar: one character at a time

getchar() reads a single character and returns it as an int. When the input is exhausted it returns EOF. It returns int rather than char precisely so that EOF can be told apart from every real character, so store the result in an int:

C Counting characters with getchar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints 24 characters, 2 lines, 5 lowercase vowels. The newlines are characters too: 13 for Hello, world! plus 1, then 9 for C is fun. plus 1. The expression (c = getchar()) != EOF reads a character, stores it, and compares it with EOF, all at once. The extra parentheses are required, because != binds more tightly than =.

getc, fgetc and getchar compared

C has three standard ways to read one character, and they are closely related:

Function Reads from Notes
fgetc(stream) any stream A real function.
getc(stream) any stream Same result as fgetc, but may be implemented as a macro that evaluates stream more than once.
getchar() stdin Exactly getc(stdin).

All three return an int holding the character as an unsigned char value (0 to 255), or EOF (a negative number, usually -1) when no more data is available. Because they behave the same, the difference is mostly about where the data comes from. Use getchar() for standard input and fgetc(f) for a file. Avoid getc(*p++): if getc is a macro, p may be incremented twice. fgetc is always safe with side effects.

The functions share one more trick. ungetc(c, stream) pushes one character back, so the next read returns it again. Parsers use this to peek: read a character, decide it belongs to the next token, and give it back.

C getchar, getc, fgetc and ungetc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The loop reads 1, 2 and the newline, so it prints 3 more characters. After the loop feof is true and ferror is false: the input simply ended. Both flags are explained in File Handling Basics.

Why the result must be an int

EOF has to be different from every valid character, which is why the return type is int. Storing the result in a char breaks that, as the next program shows. It writes the three bytes A, 0xFF and B to a file and counts them back two ways:

C char versus int and EOF

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With int you get the correct 3. With char the byte 0xFF becomes -1 on platforms where plain char is signed (such as x86), so the loop mistakes real data for EOF and stops after one byte. On platforms where char is unsigned, the loop never ends at all, because a char can never equal -1. Either way the fix is the same: int c.

getch and getche: non-standard console input

Old DOS and Windows tutorials use getch() and getche() from <conio.h>. They are not part of standard C:

  • getch() reads one key press immediately, without waiting for Enter and without echoing it. It is used for "Press any key" prompts and password entry.
  • getche() is the same but echoes the character to the screen.

Compilers for Unix-like systems do not ship <conio.h>, so #include <conio.h> fails on Linux and macOS, and it fails on our runner as well. The reason is that getchar is line-buffered: the terminal driver hands your program a line only when the user presses Enter. To read single keys, you have to switch the terminal out of canonical mode. On POSIX systems the portable tool is termios:

C
#include <stdio.h>
#include <termios.h>
#include <unistd.h>

/* A POSIX stand-in for getch(): one key, no Enter, no echo. */
int read_key(void) {
    struct termios saved, raw;
    if (tcgetattr(STDIN_FILENO, &saved) != 0) {
        return getchar();                    /* not a terminal: fall back */
    }
    raw = saved;
    raw.c_lflag &= ~(ICANON | ECHO);         /* no line buffering, no echo */
    tcsetattr(STDIN_FILENO, TCSANOW, &raw);

    int key = getchar();

    tcsetattr(STDIN_FILENO, TCSANOW, &saved);   /* always restore the terminal */
    return key;
}

To get the getche() behavior, clear only ICANON and leave ECHO set. This example is read-only because it needs a real terminal, which an in-browser runner does not have. Whatever you do, restore the saved settings before the program exits, or the user's shell is left without echo. On Windows, use _getch() from <conio.h>, which Microsoft's compiler provides, and write a small wrapper so the rest of your program stays portable.

For programs that must work everywhere, a good habit is to avoid single-key input unless the program really needs it, and to read a whole line with fgets instead.

Reading until the end of input

Real programs often don't know how many values are coming. Keep reading until the read function reports failure: scanf stops returning 1, fgets returns NULL, getchar returns EOF:

C Summing numbers until the input ends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints Read 6 numbers, sum = 63 and Average = 10.50. In our editor, the input ends where the Input box ends. In a terminal, you signal the end of input by pressing Ctrl+D on Linux and macOS, or Ctrl+Z then Enter on Windows. When input comes from a file (./program < numbers.txt), the end of the file is the end of input.

Choosing the right tool

Situation Use
Quick experiment, trusted input scanf with its return value checked
A line of text with spaces fgets, then strip the newline
A number from a user fgets + strtol/strtod (or sscanf)
Processing text character by character getchar in a loop until EOF
Several values per line in a known format fgets + sscanf, checking its return value

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The input is 7 x 9. What does scanf("%d %d %d", &a, &b, &c) return?

    It stores 7 in a, then fails at x and stops. One value was stored, so it returns 1. b and c are left unchanged.
  2. 2. Why must you write scanf("%d", &n) rather than scanf("%d", n)?

    C passes arguments by value. To change n, scanf needs to know where n lives in memory, which &n provides.
  3. 3. After scanf("%d", &n); reads 5 from the line 5, the next call is scanf("%c", &ch);. What is in ch?

    The newline after 5 is still in the input, and %c reads any character. Use " %c" to skip whitespace first.
  4. 4. What is the main advantage of fgets(buf, sizeof buf, stdin) over scanf("%s", buf)?

    fgets stops at size - 1 characters and reads the whole line including spaces. It keeps the newline, which you remove yourself.
  5. 5. Why should the result of getchar() be stored in an int, not a char?

    getchar returns any character value or EOF, which is a negative int. A char can't reliably hold all of those distinct values.

Summary

  • Input comes from stdin; in our editors, from the Input box (input presets it on every example).
  • scanf needs addresses (&x), uses %lf for double, and returns how many values it stored: always check it.
  • Numeric specifiers skip whitespace, but %c doesn't; write " %c". Give %s a width like %19s.
  • fgets(buf, sizeof buf, stdin) reads a line safely; strip the newline with buf[strcspn(buf, "\n")] = '\0'. Never use gets.
  • Read a line, then convert it with strtol or sscanf to validate numbers robustly.
  • getchar returns an int; loop while ((c = getchar()) != EOF) to process input until it ends.

Next: Keywords and Identifiers, where you'll learn C's reserved words and how to name things well.