Part 1 · Lesson 3
User Input
- interactive
On this page
What you'll learn: reading numbers and characters from the keyboard with
scanf, why it needs&, and how to check that it worked.Before you start: Lessons 1 and 2.
So far, our programs have been one-way streets: they run and print things without any input from the outside world. To build truly useful tools, we need our programs to be interactive.
The scanf Function
The counterpart to printf (for printing) is scanf (for scanning/reading).
The scanf function reads formatted input from the standard input, which is
usually your keyboard.
Like printf, it uses FORMAT SPECIFIERS to know what type of data to expect.
However, it has one very important new requirement we will explore.
To read input, we first need a variable to store that input in.
We DECLARE an integer variable user_age and INITIALIZE it to 0. The user
will provide the real value, but if reading fails, the variable still holds a
known value instead of leftover garbage from memory.
int user_age = 0;
It's good practice to print a "prompt" to the user, so they know what you're asking for:
printf("Please enter your age (as a whole number): ");
Now, we call scanf. This is the most important part of the lesson:
scanf("%d", &user_age)
-
"%d": This is the format specifier. It tellsscanfto look for and read an integer from the keyboard input. -
&user_age: This is new! The&symbol is the ADDRESS-OF OPERATOR. It gets the memory address of theuser_agevariable.
Why Do We Need &?
You must tell scanf where in memory to store the data it reads.
Simply providing user_age would only give scanf the variable's
current value (which is just 0 at this point). By providing &user_age,
you are giving it the location of the box, so it can put the user's
input directly into it.
Checking That scanf Worked
Users do not always type what you ask for. What if they type abc instead of
a number? Then scanf cannot read an integer, and user_age is left unchanged.
Luckily, scanf tells us how it went. It RETURNS the NUMBER OF ITEMS it
successfully read and stored:
1means it read our one integer. Success!0means the input did not match%d(for example,abc).EOF(a special negative value from<stdio.h>) means there was no input left at all. You can cause this by pressing Ctrl+D (Linux/macOS) or Ctrl+Z then Enter (Windows) instead of typing a number.
So we compare the result to 1:
if (scanf("%d", &user_age) != 1)
{
printf("Could not read a whole number. Exiting.\n");
return 1;
}
This means: "if scanf did NOT read exactly 1 item, print a message and stop
the program." You will learn exactly how if and != work in Lessons 4 and 5.
For now, recognize the pattern, because you should use it every time you call
scanf. return 1; ends main early with an exit code that signals an error.
Reading Other Types
The pattern is the same for other data types. We just need to change the variable type and the format specifier:
double user_gpa = 0.0;
printf("Please enter your GPA (e.g., 3.8): ");
if (scanf("%lf", &user_gpa) != 1)
{
printf("Could not read a number. Exiting.\n");
return 1;
}
printf("Your GPA is %.2f.\n", user_gpa);
IMPORTANT: For scanf, the format specifier for a double is %lf
(which stands for "long float"). This is DIFFERENT from printf,
which uses %f for a double. This is a common point of confusion!
The Leftover Newline
scanf can sometimes behave in unexpected ways because of how it handles
whitespace (like spaces, tabs, and newlines).
When you typed your GPA and pressed Enter, the \n (newline character)
was left behind in the INPUT BUFFER. A subsequent scanf call for a
character (%c) would read that leftover newline instead of waiting for
you to type a new character!
THE FIX: To fix this, we put a single space before the %c in the format
string: " %c". That leading space tells scanf to "skip any and all
leading whitespace characters before reading the character". It's a crucial trick:
if (scanf(" %c", &favorite_letter) != 1)
Full Source
/**
* @file 3_user_input.c
* @brief Part 1, Lesson 3: User Input
* @author dunamismax
* @date 06-15-2025
*
* This lesson demonstrates how to make programs interactive by reading
* input from the user's keyboard.
*/
/*
* =====================================================================================
* | - LESSON START - |
* =====================================================================================
*
* So far, our programs have been one-way streets: they run and print things
* without any input from the outside world. To build truly useful tools,
* we need our programs to be interactive.
*
* THE `scanf` FUNCTION
* The counterpart to `printf` (for printing) is `scanf` (for scanning/reading).
* The `scanf` function reads formatted input from the standard input, which is
* usually your keyboard.
*
* Like `printf`, it uses FORMAT SPECIFIERS to know what type of data to expect.
* However, it has one very important new requirement we will explore.
*/
#include <stdio.h>
int main(void)
{
// --- Part 1: Reading an Integer ---
/*
* To read input, we first need a variable to store that input in.
* We DECLARE an integer variable `user_age` and INITIALIZE it to 0. The user
* will provide the real value, but if reading fails, the variable still
* holds a known value instead of leftover garbage from memory.
*/
int user_age = 0;
/*
* It's good practice to print a "prompt" to the user, so they know
* what you're asking for.
*/
printf("Please enter your age (as a whole number): ");
/*
* Now, we call `scanf`. This is the most important part of the lesson.
*
* - `"%d"`: This is the format specifier. It tells `scanf` to look for
* and read an integer from the keyboard input.
*
* - `&user_age`: This is new! The `&` symbol is the ADDRESS-OF OPERATOR.
* It gets the memory address of the `user_age` variable.
*
* WHY DO WE NEED `&`?
* You must tell `scanf` *where* in memory to store the data it reads.
* Simply providing `user_age` would only give `scanf` the variable's
* *current value* (which is just 0 at this point). By providing `&user_age`,
* you are giving it the *location* of the box, so it can put the user's
* input directly into it.
*
* CHECKING THAT `scanf` WORKED
* Users do not always type what you ask for. What if they type `abc`
* instead of a number? Then `scanf` cannot read an integer, and `user_age`
* is left unchanged.
*
* Luckily, `scanf` tells us how it went. Like many functions, it RETURNS a
* value: the NUMBER OF ITEMS it successfully read and stored.
* - `1` means it read our one integer. Success!
* - `0` means the input did not match `%d` (for example, `abc`).
* - `EOF` (a special negative value from <stdio.h>) means there was no input
* left at all. You can cause this by pressing Ctrl+D (Linux/macOS) or
* Ctrl+Z then Enter (Windows) instead of typing a number.
*
* So we compare the result to 1. The `if` statement below means: "if `scanf`
* did NOT read exactly 1 item, print a message and stop the program." You
* will learn exactly how `if` and `!=` ("not equal to") work in Lessons 4
* and 5. For now, recognize the pattern, because you should use it every
* time you call `scanf`.
*
* `return 1;` ends `main` early. Remember from Lesson 1 that returning 0
* means success, so returning 1 tells the operating system something went
* wrong.
*/
if (scanf("%d", &user_age) != 1)
{
printf("Could not read a whole number. Exiting.\n");
return 1;
}
// Let's print the value to confirm we received it correctly.
printf("Thank you. You entered %d.\n", user_age);
printf("\n"); // Add a blank line for spacing.
// --- Part 2: Reading a Double ---
/*
* The pattern is the same for other data types. We just need to change
* the variable type and the format specifier.
*
* IMPORTANT: For `scanf`, the format specifier for a `double` is `%lf`
* (which stands for "long float"). This is DIFFERENT from `printf`,
* which uses `%f` for a `double`. This is a common point of confusion!
*/
double user_gpa = 0.0;
printf("Please enter your GPA (e.g., 3.8): ");
if (scanf("%lf", &user_gpa) != 1) // Use %lf for reading a double!
{
printf("Could not read a number. Exiting.\n");
return 1;
}
printf("Your GPA is %.2f.\n", user_gpa); // Use %f for printing a double.
printf("\n");
// --- Part 3: A Common `scanf` Pitfall and Reading a Character ---
/*
* `scanf` can sometimes behave in unexpected ways because of how it handles
* whitespace (like spaces, tabs, and newlines).
*
* When you typed your GPA and pressed Enter, the `\n` (newline character)
* was left behind in the INPUT BUFFER. A subsequent `scanf` call for a
* character (`%c`) would read that leftover newline instead of waiting for
* you to type a new character!
*
* THE FIX: To fix this, we put a single space before the `%c` in the format
* string: `" %c"`. That leading space tells `scanf` to "skip any and all
* leading whitespace characters before reading the character". It's a crucial trick.
*/
char favorite_letter = '?';
printf("Please enter your favorite letter: ");
if (scanf(" %c", &favorite_letter) != 1) // The space before %c is very important!
{
printf("Could not read a letter. Exiting.\n");
return 1;
}
printf("Your favorite letter is '%c'.\n", favorite_letter);
return 0;
}
/*
* =====================================================================================
* | - LESSON END - |
* =====================================================================================
*
* In this lesson, you learned the basics of making your programs interactive.
*
* Key Takeaways:
* - The `scanf()` function reads formatted input from the keyboard.
* - `scanf()` requires the ADDRESS-OF OPERATOR `&` before the variable name to know
* *where* to store the input.
* - Format specifiers for `scanf()` can sometimes be different from `printf()`.
* - For `double`: Use `%lf` with `scanf`, but `%f` with `printf`.
* - `scanf()` can leave newline characters in the input buffer, which can cause
* problems. The `" %c"` trick (with a leading space) is used to solve this
* when reading characters.
* - `scanf()` RETURNS the number of items it successfully read. Always check it:
* `if (scanf("%d", &x) != 1)` catches both bad input (`0`) and no input
* (`EOF`). Never use a variable that `scanf` failed to fill.
*
* HOW TO COMPILE AND RUN THIS CODE:
*
* 1. Open a terminal or command prompt.
* 2. Navigate to the directory where you saved this file.
* 3. Use the GCC compiler to create an executable file:
* `gcc -Wall -Wextra -std=c17 -o 3_user_input 3_user_input.c`
* 4. Run the executable:
* - On Linux/macOS: `./3_user_input`
* - On Windows (WSL): `./3_user_input`
*/How to Compile and Run
Runs the lesson in Compiler Explorer (GCC 16.2), nothing to install.
Once, before your first lesson
Install Apple's command line tools. They include the cc compiler: xcode-select --install
New to the terminal? The setup guide walks through it.
Build
$ cc -Wall -Wextra -std=c17 -o 3_user_input 3_user_input.c
Run
$ ./3_user_input
- Run these commands in the folder that holds the lesson's file. Download it as a zip.
- The program waits for your input: type an answer and press Enter.
Try It Yourself
Practise what this lesson taught. Change a copy of the lesson file, or start a new one.
- Ask for the user's birth year and print how old they turn this year.
- Run the program and type
abcat the first prompt, then run it again and press Ctrl+D. Which message do you get each time, and why? - Remove the space in
" %c"and run the program again. What happens at the letter prompt?
Try each one yourself before you look at a worked solution. The solutions,
with the reasoning in their comments, are in
exercises/03-user-input/
in the repository and
on this lesson's page on the website.
Solutions
One worked solution for each exercise above, with the reasoning in its comments. They stay closed until you open them: have a go first, then compare.
Show the solution to exercise 1 Hide the solution to exercise 1
/**
* @file 1_age_this_year.c
* @brief Lesson 3, Exercise 1: one possible solution
* @author dunamismax
* @date 11-20-2026
*
* THE EXERCISE:
* Ask for the user's birth year and print how old they turn this year.
*/
#include <stdio.h>
int main(void)
{
// The program cannot know what year it is yet (reading the computer's
// clock comes much later), so it asks for that too.
int current_year = 0;
int birth_year = 0;
printf("What year is it now? ");
if (scanf("%d", ¤t_year) != 1)
{
printf("Could not read a year. Exiting.\n");
return 1;
}
printf("What year were you born? ");
if (scanf("%d", &birth_year) != 1)
{
printf("Could not read a year. Exiting.\n");
return 1;
}
// `-` subtracts one number from the other. Lesson 4 covers it and the
// other arithmetic operators.
int age = current_year - birth_year;
printf("This year you turn %d.\n", age);
return 0;
}
/*
* Each `scanf` call is checked on its own, with the pattern from the lesson.
* If the first one fails, the program stops before it asks the second
* question, so it never calculates with a value the user did not give.
*
* HOW TO COMPILE AND RUN:
* gcc -Wall -Wextra -std=c17 -o 1_age_this_year 1_age_this_year.c
* ./1_age_this_year
*/Show the solution to exercise 2 Hide the solution to exercise 2
/**
* @file 2_what_scanf_returns.c
* @brief Lesson 3, Exercise 2: the answer, and a program that shows it
* @author dunamismax
* @date 11-20-2026
*
* THE EXERCISE:
* Run the program and type `abc` at the first prompt, then run it again and
* press Ctrl+D. Which message do you get each time, and why?
*
* THE ANSWER:
* You get the same message both times: "Could not read a whole number.
* Exiting." But `scanf` failed for two different reasons, and it reports
* them with two different return values. This program prints that value so
* you can see it.
*/
#include <stdio.h>
int main(void)
{
int user_age = 0;
printf("Please enter your age (as a whole number): ");
// Keep what `scanf` returns in a variable instead of comparing it
// straight away.
int items_read = scanf("%d", &user_age);
printf("\nscanf returned %d.\n", items_read);
if (items_read != 1)
{
printf("Could not read a whole number. Exiting.\n");
return 1;
}
printf("Thank you. You entered %d.\n", user_age);
return 0;
}
/*
* RUN IT THREE TIMES
*
* - Type `42`: scanf returned 1. One item was read and stored.
* - Type `abc`: scanf returned 0. There was input, but it did not look like
* a whole number, so nothing was stored and `user_age` is still 0.
* - Press Ctrl+D (Ctrl+Z then Enter on Windows): scanf returned -1. That is
* the value of `EOF` on your system. There was no input at all.
*
* The lesson's check, `!= 1`, is true for both 0 and -1. That is why one
* `if` catches both failures, and why you see the same message.
*
* HOW TO COMPILE AND RUN:
* gcc -Wall -Wextra -std=c17 -o 2_what_scanf_returns 2_what_scanf_returns.c
* ./2_what_scanf_returns
*/Show the solution to exercise 3 Hide the solution to exercise 3
/**
* @file 3_leftover_newline.c
* @brief Lesson 3, Exercise 3: what happens, and why
* @author dunamismax
* @date 11-20-2026
*
* THE EXERCISE:
* Remove the space in `" %c"` and run the program again. What happens at the
* letter prompt?
*
* THE ANSWER:
* The program does not wait for you. It prints the letter prompt and at once
* reports a "letter" that is really the Enter key you pressed after the GPA.
* This file is that broken program, so you can watch it happen.
*/
#include <stdio.h>
int main(void)
{
double user_gpa = 0.0;
printf("Please enter your GPA (e.g., 3.8): ");
if (scanf("%lf", &user_gpa) != 1)
{
printf("Could not read a number. Exiting.\n");
return 1;
}
printf("Your GPA is %.2f.\n\n", user_gpa);
char favorite_letter = '?';
printf("Please enter your favorite letter: ");
// THE BUG: no space before %c. Compare with the lesson's `" %c"`.
if (scanf("%c", &favorite_letter) != 1)
{
printf("Could not read a letter. Exiting.\n");
return 1;
}
printf("Your favorite letter is '%c'.\n", favorite_letter);
// Printing the character's code (Lesson 2, Exercise 3) shows what was
// read: 10 is the code of the newline character, `\n`.
printf("Its character code is %d.\n", favorite_letter);
return 0;
}
/*
* WHY IT HAPPENS
*
* When you type `3.8` and press Enter, four characters go into the INPUT
* BUFFER: `3`, `.`, `8` and `\n`. `%lf` takes the first three and stops at
* the newline, leaving it behind.
*
* `%d` and `%lf` skip whitespace before they start reading, so a leftover
* newline never bothers them. `%c` is different: it reads the very next
* character, whatever it is. Here that is the leftover `\n`, so `scanf`
* returns straight away, with success, and the output looks like this:
*
* Your favorite letter is '
* '.
* Its character code is 10.
*
* The space in `" %c"` means "first skip any whitespace". With it, the
* newline is thrown away and `scanf` waits for a real character.
*
* HOW TO COMPILE AND RUN:
* gcc -Wall -Wextra -std=c17 -o 3_leftover_newline 3_leftover_newline.c
* ./3_leftover_newline
*/Finished this lesson?
Mark it complete to track your progress through the course.