Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Reading Formatted Input with scanf

Welcome to the final lesson of our first module on C programming foundations. In our last session, we learned how to use arithmetic operators to perform calculations on data that we had hardcoded into our programs. This was a crucial step, but to build truly interactive and useful applications, our programs need to get data from the outside world.

Today, we'll address this by tackling our next learning outcome: to read formatted user input from the console using scanf and store it in variables. You will learn how to make your programs pause, wait for the user to type something, and then use that input in your code. This will make your programs dynamic and able to solve different problems without needing to be recompiled.

We will focus on two key components: the format specifiers that tell scanf what kind of data to expect, and the all-important & operator that tells scanf where to store that data.

1. Introducing scanf: Reading from the Keyboard

So far, we've used the printf function to send data from our program to the console (standard output). Now, we'll learn its counterpart, scanf, which reads data from the keyboard (standard input).

The scanf function, which stands for "scan formatted", works similarly to printf in that it uses a format string with specifiers like %d for integers and %f for floats. However, its purpose is the reverse: it interprets characters from the input stream according to the format string and stores the results in variables.

The first video below gives a quick introduction.

Basic Input Function – scanf

This clip from Neso Academy's video "Basic Input Function – scanf" provides a concise overview of what scanf is and what it does.

Watch from the beginning to the introduction. Pay attention to the parallel between printf's format specifiers and those used by scanf.

A common and user-friendly practice is to use printf to display a prompt before calling scanf. This tells the user what kind of input the program is expecting.

Let's look at a simple program that asks for an integer and then prints it back.




#include <stdio.h>

int main() {
    int number;

    // 1. Prompt the user for input.
    printf("Please enter an integer: ");

    // 2. Read the integer from the keyboard and store it in 'number'.
    scanf("%d", &number);

    // 3. Print the stored value to confirm it was read correctly.
    printf("You entered: %d\n", number);

    return 0;
}

Notice the & symbol before the variable number in the scanf call. This is not optional; it is fundamental to how scanf works, and we'll explore exactly why in the next section.

2. The Ampersand (&): The "Address-Of" Operator

This is the most critical concept in this lesson. When we use printf, we give it a variable's value to display. But scanf needs to change a variable's value. To do this, it can't just receive a copy of the value; it needs to know the variable's location in memory.

The ampersand & is C's address-of operator. When placed before a variable name (e.g., &number), it doesn't give you the value of number but instead provides its unique memory address.

Think of it like this:

  • printf("Your number is %d", number); means "Here is the value 5, please print it."
  • scanf("%d", &number); means "Please take the user's input and store it at memory location 0x7ffee..., which is where number lives."

The following videos explain this crucial concept from two slightly different angles. The first is a direct explanation, and the second uses a visual model of memory that you might find connects well with your software development background.

Basic Input Function – scanf

This section from the Neso Academy video provides a clear and direct explanation for why the ampersand is necessary.

Watch the segment from Why we use &. The key idea is that scanf needs to know the memory location to store the data.

The next video offers a more in-depth, visual explanation related to how functions manage memory. It briefly mentions the concept of a pointer, which is a variable that stores a memory address. We will cover pointers in great detail in a future module, but this explanation provides the correct mental model for what's happening.

Input and Output: Printf and Scanf - C Programming Tutorial 06

Watch this segment from mycodeschool's "Input and Output" video for a deeper dive into the 'why' behind the ampersand.

Focus on the explanation from the memory model. The visual of memory blocks for each function helps clarify why passing an address is necessary for scanf to modify a variable in main.

3. Reading Multiple Values and Different Types

You can read multiple inputs with a single scanf call. You simply provide a format specifier for each variable and a corresponding variable address. The way you separate the inputs when you type them (e.g., with a space or a newline) is also important.

This reading from freeCodeCamp demonstrates reading multiple values and reinforces the use of the address-of operator.

How to Use scanf( ) in C to Read and Store User Input

This article provides clear examples and explanations for reading different data types.

Read the sections "How to Use Conversion Specifiers to Read Input" and "How to Store Input in Variables Using Pointers". They provide code examples for reading an int and a float in one line and re-emphasize the role of the & operator.

Here's a list of the most common format specifiers you will use with scanf:

Specifier Data Type Example Variable
%d int int count;
%f float float price;
%lf double double pi;
%c char char initial;

Whitespace Handling: scanf is smart about whitespace (spaces, tabs, newlines). When reading numbers, it will automatically skip any whitespace characters between the inputs. So, if your code is scanf("%d %d", &a, &b);, you could enter 10 20, or 10 then Enter then 20, and the result would be the same.

4. Practical Exercise: A Simple Calculator

Let's combine today's lesson with what we learned about arithmetic operators. Your task is to build a program that asks the user for two numbers and then calculates their sum, difference, product, and quotient.

Action: Create a new file named calculator.c. Type, compile, and run the following code. Experiment with different integer and floating-point numbers.




#include <stdio.h>

int main() {
    float num1, num2;

    printf("Enter the first number: ");
    scanf("%f", &num1);

    printf("Enter the second number: ");
    scanf("%f", &num2);

    printf("\n--- Calculations ---\n");
    printf("%.2f + %.2f = %.2f\n", num1, num2, num1 + num2);
    printf("%.2f - %.2f = %.2f\n", num1, num2, num1 - num2);
    printf("%.2f * %.2f = %.2f\n", num1, num2, num1 * num2);

    // Add a check to prevent division by zero
    if (num2 != 0) {
        printf("%.2f / %.2f = %.2f\n", num1, num2, num1 / num2);
    } else {
        printf("Cannot divide by zero.\n");
    }

    return 0;
}

This example introduces an if statement, which we will formally cover in the next module. For now, just know that it checks if num2 is not equal to zero before attempting the division—a good practice to prevent runtime errors.

5. A Note on Robustness: Checking scanf's Return Value

Professional code is robust code. What happens in our calculator if the user types "hello" instead of a number? The program might crash or behave unpredictably.

scanf provides a mechanism to help with this. It returns a value: the number of items it successfully read and assigned. If you expect to read two numbers (scanf("%f %f", ...)), a successful call will return 2. If the user enters one valid number and then invalid text, it will return 1. If the input is immediately invalid, it will return 0.

How to Use scanf( ) in C to Read and Store User Input

This final section from the freeCodeCamp article introduces a crucial concept for writing more reliable programs.

Read the section "Input Validation and Error Checking". It shows how to use an if statement to check the return value of scanf and handle invalid input gracefully.

While we won't require this level of error checking in our early exercises, it's an important habit to be aware of as you progress.

Conclusion

You have now completed the foundations of C programming! You can declare variables to store data, use operators to process it, and use printf and scanf to communicate with the user.

Key Takeaways:

  • scanf reads formatted input from the keyboard, acting as the counterpart to printf.
  • It uses format specifiers like %d, %f, and %lf to know what data type to expect.
  • The address-of operator (&) is mandatory for variables passed to scanf. It provides the memory location where the input data should be stored.
  • You can read multiple values in a single scanf call, and it automatically handles whitespace between numeric inputs.
  • For more robust programs, you can check the integer value returned by scanf to see how many items were successfully read.

In our next module, "Controlling Program Flow," we will move beyond writing code that executes straight from top to bottom. You will learn how to make decisions using if-else statements and how to repeat actions using loops. This will unlock the ability to write much more powerful and intelligent programs.

Can't find a good explanation? Sign up and we'll make it for you

Sign up