scanf() in C Tutorial

In this section, we will learn what the scanf() function is and how to use it in C.

Note: we’re assuming you’re already familiar with the printf() function in C.

What is scanf() Function in C?

There are times when we want to get input from a user like her username or password or personal information, etc., this is where we can use `scanf` function.

Basically, the scanf() function is used to get inputs from users and so it’s a way of letting users to interact with a program by sending data to it.

Note: The prototype of `scanf` function is declared in the `<stdio.h>` header file and so we need to include this header in the program that uses `scanf` function.

`#include <stdio.h>`

There are many similarities between the `printf` and `scanf` functions! Both take character-string as the first argument and within the character-string we would use the format-specifiers.

C scanf() Function Syntax:

Here’s the prototype of `scanf` function:

int scanf(const char *format, ...);

The first argument of this function, as mentioned before, is the character-string.

Other than character-string as the first argument of the `scanf` function, the rest of arguments are the address of the memory spaces that we want to store the entered inputs by users in those memory spaces.

Basically, when a user enters a data into a program, this data must be stored in a memory space first and then we use the address of that memory space to access the value and run any necessary operation afterward.

So, depending on the number and the data type of values that a program asks from users to enter (using the scanf() function) we put the memory address of one or more variables as the rest of arguments to this function and this function stores the entered values to these variables then. Now we can use the variables to interact with the entered data.

The `scanf` function return value:

The `scanf` function returns the number of items that it successfully reads. If it reads no items, which happens if you type a nonnumeric string when it expects a number, the `scanf` function will return the value 0.

Note that this function can also be used to read files. Now when using the function to read a file, it might return the value `EOF` when it detects the condition known as the “end of file”. Typically, this value is equal to -1 which means the function reached the end of the target file and there’s nothing left to be read.

Note: you can learn more about EOF in the File Input/Output section.

Example: using scanf() function in C

#include <stdio.h>

int main() {

    int age ;
    printf("Please enter you age: \n");

    scanf("%d",&age);

    printf("Your age is: %d\n", age);
    return 0;
}

Memory Address in C:

Let’s say we have a variable like this in a program: `int age = 10`.

The `age` variable here is actually the pointer of a memory-space that currently contains the value 10.

So if we call this variable like this: `int secondAge = age`.

When the CPU sees this statement, it knows that it should go and find the memory location that the `age` variable is pointing at, take a copy of the value that is currently stored there and then store this copied value to the memory space that the secondAge variable is pointing at.

As you can see, calling a variable by name allows us to access its value.

But a function like `scanf` does not need the value of a variable and instead it needs the memory address of a variable, so when a user entered a value, that value can be stored in that memory space.

Now, in order to access the `address` of a memory space that a variable is pointing at, we put ampersand `&` on the left side of the target variable.

Example: taking the memory address in C

#include <stdio.h>

int main() {

    int age ;

    printf("The memory address of the age-variable is: %p", &age);

    return 0;
}

Output:

The memory address of the age-variable is: 000000000022FE4C

Note:

  • As you’ll learn in the array-section, for variables that point to an array, we don’t need to use the ampersand in order to get the memory address! Calling the variable itself will give you the memory address where the array is stored in.

Also, as mentioned before, both functions printf() and the scanf() take format-specifiers. But the difference is that in the `printf` function, we use the format-specifiers to declare how the already existed data in the memory should be translated and sent to an output stream. But on the contrary, the use of format-specifiers in the `scanf` function is to declare the type of memory that we use as the argument of this function and so how the incoming data should be converted and stored in the target memory location.

At the beginning of this section, we used this example:

#include <stdio.h>

int main() {

    int age ;
    printf("Please enter you age: \n");

    scanf("%d",&age);

    printf("Your age is: %d\n", age);
    return 0;
}

Here, we’ve created the `age` variable and then used its address as the second argument in the `scanf` function with the help of ampersand `&`.

Now, if we compile and run this example, the program wants us to enter our age and the value we enter to the program will be stored in the memory space that the `age` variable is pointing at.

Note: because the conversion-specification here in this example is `%d` we’re only allowed to use integer values like 32, 50, 28, and 20, etc.

For this example, if we entered a number with the fraction part, the fraction part will not be stored in the `age` variable.

Example: C scanf() function

#include <stdio.h>

int main() {

    int age ;

    int numberOfSiblings;
    printf("Please enter you age and the number of your siblings: \n");

    scanf("%d%d",&age , &numberOfSiblings);

    printf("Your age is: %d and you have %d siblings", age , numberOfSiblings);

    return 0;
}

Output:

Please enter you age and the number of your siblings:

28 4

Your age is: 28 and you have 4 siblings

First and foremost, you should know that the `scanf` function uses the whitespace like (newline, tab and spaces) to decide how to divide inputs into separate fields.

For example, if we entered 5 input values and each is separated by either a space or a tab or a new line, the scanf function considered them as 5 inputs and not just one!

And so, if we put 5 memory addresses as the arguments of this function, it’ll fill all 5 memory spaces with inputs it got from the user.

So when the program is running, we put the first number for the age question and then the second number comes after we put a space after the first number. Now the program recognizes that there are two values entered by a user and so it will assign the first number to the `age` variable and the second number to the `numberOfSiblings`.

Note: you can set one memory address as the argument of the `scanf` function but enter multiple inputs as well! Let’s see how this possible:

How Does scanf() Function Work in C?

You see, the `scanf` function is supported by a buffer (memory space) in the memory.

Any input value we enter; it’ll be stored in that buffer first.

After that, the `scanf` function will check the conversion-specification to see how many of these specifiers it has and it will try to convert and translate the entered data into the right type (based on the declared specifiers) and store it in the related memory space of the addresses declared in the `scanf` function (as the arguments of this function).

Example:

#include <stdio.h>

int main() {

    int age ;

    int numberOfSiblings;
    printf("Please enter you age and the number of your siblings: \n");

    scanf("%d",&age );
    scanf("%d" , &numberOfSiblings);

    printf("Your age is: %d and you have %d siblings", age , numberOfSiblings);

    return 0;
}

Output:

Please enter you age and the number of your siblings:

20 2

Your age is: 20 and you have 2 siblings

In this example, we called the `scanf` function two times!

When the program ran, we entered two numbers; the first number is for the `age` variable and followed by that, we added a space and then the second number is for the number of siblings.

First, these two numbers and the space are stored in the buffer of the `scanf` function.

After that, the first call to the scanf function checked this buffer to see if there’s a data of type number.

Note: if the conversion-specification is anything other than the `%c` specifier which is for character reading, the scanf function will skip any white-space entered by a user until it reaches the actual non-white-space data.

So the first `scanf` function will skip any white-space until it encounters data of type integer. Because the first entered value is of type integer, the data will be moved and stored in the memory space of the `age` variable, because this is the argument of the first `scanf` function.

Then the second call to the `scanf` function happened in the program, which in that case, again the buffer of the `scanf` will be checked first to see if there’s a data of type integer or not.

Because there’s another input, the second `scanf` function will take that number and stores it in the memory space that the `numberOfSiblings` variable is pointing at.

And that’s how the data entered by users read and stored in each variable.

Note: if there’s no data in the buffer, the call to `scanf` function will stop the program and ask users to enter an input before moving on to the rest of the program.

C scanf() Function and Format Specifiers

Here’s the list of format specifiers that can be used in the `scanf` function:

Format Specifiers Meaning
%c Interpret input as a character.
%d Interpret input as a signed integer.
%e, %f, %g, %a Interpret input as a floating-point number (%a is C99)
%E, %F, %G, %A Interpret input as a floating-point number (%A is C99)
%i Interpret input as a signed integer.
%o Interpret input as a signed octal integer.
%p Interpret input as a pointer (an address).
%s Interpret input as a string. Input begins with the first non-whitespace character and includes everything up to the next whitespace character.
%u Interpret input as an unsigned integer.
%x, %X Interpret input as a signed hexadecimal integer.

The table above is taken from the C Primer Plus, 6th Edition Book

We can also use the conversion-specification modifiers as well.

Here’s the list of modifiers:

Modifier Meaning
* Suppress assignment

Example: “%*d”

Digit(s) Maximum field width. Input stops when the maximum field width is reached or
when the first whitespace character is encountered, whichever comes first
.

Example: “%10s”

hh Read an integer as a signed char or unsigned char.

Example: “%hhd” “%hhu”

ll Read an integer as a long long or unsigned long long

Example: “%lld” “%llu”

h,l, or L “%hd” and “%hi” indicate that the value will be stored in a short int. “%ho”, “%hx”, and “%hu” indicate that the value will be stored in an unsigned short int. “%ld” and “%li” indicate that the value will be stored in a long. “%lo”, “%lx”, and “%lu” indicate that the value will be stored in unsigned long.
“%le”, “%lf”, and “%lg” indicate that the value will be stored in type double.
Using L instead of l with e, f, and g indicates that the value will be stored in type long double. In the absence of these modifiers, d, i, o, and x indicate type int, and e, f, and g indicate type float.
j When followed by an integer specifier, indicates using the intmax_t or
uintmax_t type (C99).
Examples: “%jd” “%ju”.
z When followed by an integer specifier, indicates using the type returned by
sizeof (C99).
Examples: “%zd” “%zo”.
t When followed by an integer specifier, indicates using the type used to represent
the difference between two pointers (C99).
Examples: “%td” “%tx”.

The table above is taken from the C Primer Plus, 6th Edition Book

Example: scanf() function and format specifiers

#include <stdio.h>

int main() {

    char firstLetter;

    printf("Please enter the first letter of your first name: \n");
    
    scanf("%c",&firstLetter);

    printf("The first letter of your name is: %c", firstLetter);

    return 0;
}

Output:

Please enter the first letter of your first name:

O

The first letter of your name is: O

Example: scanf function return value

#include <stdio.h>

int main() {

    float height;

    printf("Please enter your height: \n");

    int number = scanf("%f",&height);

    printf("The height is: %.1f\n", height);
    printf("Also the returned value of the scanf function is: %d\n", number);

    return 0;
}

Output:

Please enter your height:

6.0

The height is: 6.0

Also, the returned value of the scanf function is: 1

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies