Table of contents
1.
Introduction
2.
What is scanf in C?
3.
Syntax of Scanf
4.
Example Format Specifiers Recognized by scanf
5.
Return Value of scanf
6.
Why Scanf is Important?
7.
Example of scanf
7.1.
C
8.
Frequently Asked Questions
8.1.
What happens if I use the wrong format specifier in scanf?
8.2.
Can scanf read more than one input at a time?
8.3.
Why do I sometimes need to put a space before %c in scanf?
9.
Conclusion
Last Updated: Jan 15, 2025
Easy

Scanf In C

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In C programming, there is a very important function which interacts with user straightforwardly, it’s scanf function, a simple yet powerful tool for reading formatted input from the standard input stream, typically the keyboard. This function enables a program to accept user input in a structured and controlled manner, making it an indispensable part of creating interactive applications.

Scanf In C

In this article, we'll learn about its syntax, the variety of format specifiers it supports, its return values, and the crucial role of the '&' operator.

What is scanf in C?

scanf is a standard input function in C that reads formatted data from the user. It allows the user to input values, which are stored in the specified variables. The function is commonly used for reading different data types, such as integers, floating-point numbers, and strings, based on a format specifier.

Syntax of Scanf

To make a program do something useful, like solving a problem or performing a task, we often need to talk to it, tell it what we want by typing in some data. That's where scanf comes into play in C programming. It's like asking for specific details: "What's your name?" or "How old are you?". In coding terms, scanf allows your program to ask for these details.

The way you write scanf in your code is pretty straightforward. You start with the word scanf, followed by parentheses (). Inside these parentheses, you first put what kind of information you're asking for, wrapped in quotes "", and then you tell the program where to store this information.

Here's a simple way to look at it:

scanf("format specifier", &variable);

 

  • "format specifier" tells the program what kind of data you're expecting, like a number or a letter.
     
  • &variable is the place in the program where you want to keep the data that the user gives.
     

It's crucial to match the right format specifier with the kind of data you're asking for, or else the program might get confused and not work right. 

Example Format Specifiers Recognized by scanf

When we use scanf in our programs, it's like filling in a form where each blank space has a specific type of information it needs. In programming with C, these "blank spaces" are defined by what we call format specifiers. They tell scanf what type of data we're expecting from the user. Think of it as labeling jars in the kitchen for sugar, salt, and spices; each jar should contain the right ingredient. Here are some common "labels" (format specifiers) that scanf uses:

  • %d for whole numbers (integers). Example: 5, -3, 42.
     
  • %f for floating-point numbers (decimals). Example: 3.14, -0.001, 2.718.
     
  • %c for single characters. Example: 'a', 'Z', '3'.
     
  • %s for strings (a sequence of characters). Example: "hello", "1234".
     

When you write scanf, you choose the right specifier for the data you want. For instance, if you want an age, you use %d because age is a whole number. If you're going to get the first letter of someone's name, you use %c because it's a single character.

Here's an example:

int age;
char firstLetterOfName;
scanf("%d", &age); // For an integer
scanf("%c", &firstLetterOfName); // For a character

In these lines, the first scanf expects an integer value from the user and stores it in the variable age. The second scanf awaits a single character and saves it in firstLetterOfName.

Return Value of scanf

Every time you use scanf in a C program, it's not just about getting input. scanf also tells you something back. It gives you a number that shows how many items it successfully read. This is what we call the return value of scanf.

Imagine you ask for two things: a number and a letter. If you get both correctly, scanf returns 2, meaning "I got 2 pieces of information as asked." If you only get the number right, scanf might return 1, saying "I only got 1 out of 2 right."

Here's how you can see this in a program:

int number;
char letter;
int result = scanf("%d %c", &number, &letter);


In this example, result will store the return value of scanf. If the user enters a number and a letter correctly, result will be 2. If something goes wrong, like the user doesn't enter the right type of data, result might be 1 or even 0, indicating how many items were successfully read.

Why Scanf is Important?

  • User Input: scanf is essential for reading user input from the console, allowing programs to interact with users dynamically.
  • Data Flexibility: It supports various format specifiers, enabling the input of different data types such as integers, floating-point numbers, and strings.
  • Real-time Data Handling: scanf provides a simple way to capture values during the program's execution, making it useful for interactive applications.
  • Input Validation: While not a built-in feature, scanf can be used with additional checks to validate and sanitize user input, ensuring reliable program behavior.
  • Efficiency: It allows for direct reading of multiple values in a single line, making input operations efficient in C programs.

Here's a simple example:

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


In this code, age is a box where you want to store a number. The %d tells scanf you're expecting an integer. The & before age helps scanf understand that it should put the number it gets into the age box.

The & is crucial because it ensures that the data goes to the right place. If you forget it, scanf won't work as expected, and your program might not behave correctly.

Example of scanf

Let's put everything we've talked about into practice with a simple example. We'll write a small program that asks for a user's age and their favorite letter of the alphabet, then prints these details back to the screen.

Here's the code:

  • C

C

#include <stdio.h>

int main() {
int userAge;
char favoriteLetter;

printf("Enter your age: ");
scanf("%d", &userAge);

// To read a single character after an integer input, we need to include a space before %c in the format string.
// This is because scanf leaves the newline character in the buffer after reading the integer,
// and we need to consume it before reading the next character.
printf("Enter your favorite letter: ");
scanf(" %c", &favoriteLetter);

printf("You are %d years old and your favorite letter is %c.\n", userAge, favoriteLetter);

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Enter your age: 27
Enter your favorite letter: G R
You are 27 years old and your favorite letter is R.


In this program:

  • We first declare two variables, userAge for storing the age and favoriteLetter for storing the letter.
     
  • We then use printf to ask the user for their age and use scanf("%d", &userAge) to read and store the age. %d tells scanf we want an integer, and &userAge points to where to store it.
     
  • Next, we ask for the favorite letter. Notice the space before %c in scanf(" %c", &favoriteLetter). This space is essential because it tells scanf to skip any whitespace characters (like the newline character left from entering the age) before reading the next character.
     
  • Finally, we use printf to show the entered age and favorite letter.

Frequently Asked Questions

What happens if I use the wrong format specifier in scanf?

Using the wrong format specifier can lead to unexpected results. For example, if you use %d (for integers) when you should use %f (for floating-point numbers), scanf might not read the input correctly, and your program could behave unpredictably.

Can scanf read more than one input at a time?

Yes, scanf can read multiple inputs in one go. You just need to provide the right format specifiers and variables. For instance, scanf("%d %c", &age, &letter) can read an integer and a character sequentially from the same line of input.

Why do I sometimes need to put a space before %c in scanf?

The space before %c tells scanf to ignore any whitespace characters (like spaces or newline characters) before reading the next non-whitespace character. This is often needed after reading a different type of input, like an integer, to avoid having scanf read the leftover newline character as the character input.

Conclusion

In this article, we learned everything about the scanf function in C, starting with its basic syntax and then we talked about the various format specifiers it supports. We've also discussed its return value, which gives us an idea  into how many inputs were successfully read, and highlighted the significance of the & operator in directing input to the right memory locations. 

Live masterclass