Table of contents
1.
Introduction
2.
scanf Syntax
3.
Example Format Specifiers Recognized by scanf
4.
Example of Using scanf
4.1.
C
5.
Return Value of scanf
5.1.
C
6.
Why Use the & Operator in scanf?
6.1.
C
7.
Example of scanf
7.1.
Example 1: Reading Single Values
7.2.
C
7.3.
Example 2: Reading Multiple Values
7.4.
C
7.5.
Example 3: Reading Strings
7.6.
C
8.
Frequently Asked Questions
8.1.
What happens if the wrong format specifier is used in scanf?
8.2.
Can scanf handle spaces in strings?
8.3.
How can I check if scanf read the input correctly?
9.
Conclusion
Last Updated: May 5, 2024
Medium

Scanf Function in C

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

Introduction

The scanf function in C is used to read input from the user through the keyboard. It allows programs to accept data entered by the user & store it in variables for further processing. 

Scanf Function in C

In this article, we will talk about the scanf function in detail, including its syntax, format specifiers, return value, & usage with the & operator. We will understand every concept with proper examples.

scanf Syntax

The basic structure of scanf looks like this:

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


Here, format refers to a string that specifies the type of data that is expected. This string contains format specifiers, which start with a % symbol, followed by a character that represents the data type of the variable where the input should be stored. The ... indicates that scanf can accept multiple inputs based on the format specifiers provided.

For example, to read an integer, you would use the %d format specifier:

int number;
printf("Enter an integer: ");
scanf("%d", &number);


In this example, %d tells scanf to expect an integer input. The &number argument is a memory address where the integer value entered by the user will be stored. It is crucial to use the & operator (address operator) with scanf because it needs to know where in memory to store the value it reads.

The function can handle multiple values at once. For instance, to read two integers simultaneously, you can use:

int age, year;
printf("Enter your age and the current year: ");
scanf("%d %d", &age, &year);


This tells scanf to expect two integer inputs, which will be stored in age and year respectively. The space between %d and %d in the format string tells scanf to expect the inputs to be separated by at least one whitespace character in the user's input.

Example Format Specifiers Recognized by scanf

scanf uses format specifiers to interpret the input types and to direct the input into the variables provided in its argument list. Each specifier corresponds to a specific type of data. Here’s a look at some common format specifiers and what they represent:

  • %d: Reads an integer value.
     
  • %c: Reads a single character.
     
  • %s: Reads a string (sequence of characters) until a whitespace is encountered.
     
  • %f: Reads a floating-point number, a number with a decimal.
     
  • %lf: Reads a double precision floating-point number.
     

For example, if you want to read a character and an integer from the user, you would use:

char letter;
int number;
printf("Enter a character and an integer: ");
scanf("%c %d", &letter, &number);


This code snippet will wait for the user to enter a character followed by an integer. The %c specifier captures the first character entered, and %d captures the integer. Note that it is important to ensure there is a space or a newline after entering the character before entering the integer to help scanf correctly parse the input.

In addition to these, there are several other specifiers for various types of data:

  • %u: Unsigned integer.
     
  • %x: Hexadecimal integer.
     
  • %o: Octal integer.
     
  • %e or %E: Floating point number in scientific notation.


Each specifier must match the corresponding variable type in the argument list of scanf. Using the wrong format specifier can lead to errors and unpredictable behavior in your program.

Example of Using scanf

Consider a scenario where we need to gather some basic information about a user: their name, age, and whether they are a new user (yes or no). Here's how you can write the C program:

  • C

C

#include <stdio.h>

int main() {
char name[50]; // Array to store the name
int age;
char isNewUser;

// Prompt the user for their name
printf("Enter your name: ");
scanf("%s", name); // Using %s to read a string

// Prompt the user for their age
printf("Enter your age: ");
scanf("%d", &age); // Using %d to read an integer

// Ask if the user is new
printf("Are you a new user? (Y/N): ");
scanf(" %c", &isNewUser); // Using %c to read a character, note the space before %c to skip any newline left in the input buffer

// Output the gathered information
printf("Welcome, %s!\n", name);
printf("Age: %d\n", age);
printf("New User: %c\n", isNewUser);

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

Output

Enter your name: Rahul
Enter your age:  3535
Are you a new user? (Y/N): Y
Welcome, Rahul!
Age: 35
New User: Y


In this program:

  • We use %s to read a string for the user’s name. Note that scanf stops reading the string once it hits a space, so this won't work for names with spaces.
     
  • The %d specifier is used to read an integer value for the age.
     
  • The %c is used to read a single character response for whether they are a new user or not. Importantly, there is a space before %c in the scanf format string. This space is crucial as it tells scanf to ignore any whitespace characters left in the input buffer (like the newline from pressing enter after the age input), ensuring that the character input for the new user question is correctly read.

Return Value of scanf

The function returns an integer that indicates how many items were successfully read and assigned. This feature can be very useful for error checking in your input operations.

Here’s how the return value works:

If successful, scanf returns the number of items fully read and assigned. For instance, if your format string asks for two integers and the user correctly inputs two integers, scanf will return 2.

If an error occurs or the end of the file (EOF) is reached before any data could be read, scanf returns EOF. Typically, EOF is represented by the integer -1.

Consider the following example where we check the return value to ensure the user inputs valid data:

  • C

C

#include <stdio.h>

int main() {
int age;
printf("Enter your age: ");
int result = scanf("%d", &age);

if (result == 1) {
printf("You entered: %d\n", age);
} else {
printf("Failed to read the age. Please enter a valid integer.\n");
}

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

Output

Enter your age: 35
You entered: 35


In this program:

  • We attempt to read an integer from the user to capture their age.
     
  • We store the return value of scanf in a variable named result.
     
  • We then check result. If it is 1, that means one item (the age) was successfully read and assigned. If not, an error message is displayed, indicating that the input was not valid.


By checking the return value of scanf, you can handle different scenarios where the input might not be as expected. This can prevent common problems like entering a letter when a number is expected, which without proper checking, could lead to unexpected behavior or crashes in more complex programs.

Why Use the & Operator in scanf?

When using scanf in C programming, the & operator plays a crucial role. This operator is used to pass the address of a variable to scanf, allowing the function to store input data directly into memory at the location of the variable. Understanding its necessity is fundamental for correctly reading user input.

Here's a breakdown of why the & operator is important:

  • Direct Memory Access: scanf needs to modify the variable given as an argument directly. By providing the address of the variable (which & does), you allow scanf to write the user's input directly to that memory location.
     
  • Avoiding Errors: Without the &, scanf might try to write to a random memory location, which can lead to program crashes or unpredictable behavior. For example, trying to use scanf to read an integer into a variable without the & results in a compilation error, as the function requires the address to store the data.

Here’s a simple illustration of using the & operator:

  • C

C

#include <stdio.h>

int main() {

   int age;

   printf("Enter your age: ");

   scanf("%d", &age);  // Notice the & before age

   printf("You entered: %d\n", age);

   return 0;

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

Output

Enter your age: 35
You entered: 35

In this code:

  1. age is a variable that will store an integer.
     
  2. When we call scanf, we use %d as the format specifier for an integer and &age to pass the address of age.
     
  3. scanf writes the integer entered by the user directly into the memory location of age, thanks to the address provided by the & operator.
     

It's important to note that for certain data types like strings (character arrays), the & operator is not needed because the name of an array already refers to its starting address.

Example of scanf

Example 1: Reading Single Values

  • C

C

#include <stdio.h>

int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("Your age is: %d\n", age);
return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Enter your age: 35
You entered: 35


Explanation:

  • The program prompts the user to enter their age.
     
  • scanf("%d", &age) reads the inputted integer and stores it in the variable age.
     
  • The entered age is then displayed using printf.

Example 2: Reading Multiple Values

scanf can also be used to read multiple values in one go. Here's how you can read an integer and a floating-point number together:

  • C

C

#include <stdio.h>

int main() {
int id;
float gpa;
printf("Enter your ID and GPA: ");
scanf("%d %f", &id, &gpa);
printf("ID: %d, GPA: %.2f\n", id, gpa);
return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Enter your ID and GPA: 350821 6.3
ID: 350821, GPA: 6.30


Explanation:

  • The user is asked to enter both an ID (integer) and a GPA (floating-point number).
     
  • scanf("%d %f", &id, &gpa) reads both values, separated by a space.
     
  • Both values are then printed to confirm the input.

Example 3: Reading Strings

Reading strings with scanf can be done using the %s specifier, but it stops reading at the first whitespace:

  • C

C

#include <stdio.h>

int main() {
char name[50];
printf("Enter your first name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Enter your first name: Himanshi
Hello, Himanshi!


Explanation:

  • The user is prompted to enter their first name.
     
  • scanf("%s", name) reads a string into the array name until it encounters a space, tab, or newline.
     
  • The name is then displayed with a greeting.

Frequently Asked Questions

What happens if the wrong format specifier is used in scanf?

If you use the wrong format specifier, scanf might cause the program to behave unpredictably, often leading to runtime errors or incorrect data being read. For instance, using %d for a float will result in incorrect values being stored.

Can scanf handle spaces in strings?

By default, %s with scanf stops reading at the first whitespace. To read a full line including spaces, you can use fgets() instead, or use a character class in scanf, like %[^\n]s, which reads until a newline is encountered.

How can I check if scanf read the input correctly?

You can check the return value of scanf, which tells how many items were successfully read. If it doesn’t match the expected number, there might have been an error in inputting data.

Conclusion

In this article, we have explored the scanf function in C, a powerful tool for reading formatted input. We've learned its basic syntax, discussed various format specifiers, and provided examples that shows how to use scanf effectively. We also talked about the significance of the & operator and examined the importance of checking the return value of scanf for robust error handling. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass