Back to C Programming
2026-07-125 min read

scanf() function

Learn scanf() function step by step with clear examples and exercises.

Why This Matters

In C programming, the scanf() function is a crucial tool for reading user input from the keyboard. It's essential to understand how to use this function effectively to write efficient and interactive programs. The scanf() function is often used during exams, interviews, and in real-world coding challenges, making it an important skill to master.

Prerequisites

Before diving into the scanf() function, you should have a good understanding of:

  1. Basic C syntax: variables, data types, operators, and control structures.
  2. Standard input/output (stdin, stdout) in C programming.
  3. Basics of formatted I/O using printf().
  4. Understanding the difference between functions and libraries in C.

Core Concept

The scanf() function is a part of the standard input/output library (stdio.h) in C programming. It reads formatted input from the standard input stream, typically the keyboard. The syntax for the scanf() function is as follows:

#include <stdio.h>
int scanf(const char *format, ...);

The scanf() function accepts a format string (format) and variable arguments corresponding to the format specifiers in the format string. The format string specifies the type of input expected and is composed of conversion specifications starting with a % character.

Format String

The format string consists of two parts:

  1. Conversion Specification: Starts with a % character followed by a character that represents the data type to be read. For example, %d for an integer, %f for a floating-point number, and %c for a character.
  2. Width and Precision Modifiers: Optional modifiers that can be used to specify additional properties of the input. These are optional and can be omitted if not needed.

Width Modifier (width)

The width modifier specifies the maximum number of characters to be read for a particular conversion specification. It is represented by an integer enclosed between * or a number in brackets ([]). For example:

  • %5d : reads up to 5 digits for an integer.
  • %[10]s : reads exactly 10 characters for a string.

Precision Modifier (precision)

The precision modifier is used with floating-point conversion specifiers (e, f, and g) to specify the number of digits after the decimal point. It is represented by a period (.) followed by an integer. For example:

  • %f : reads the floating-point number up to 6 decimal places by default.
  • %10.2f : reads the floating-point number with exactly 2 digits after the decimal point and a maximum of 10 characters.

Variable Arguments

After the format string, you can pass additional arguments corresponding to the format specifiers in the format string. Each argument must be a pointer to a variable where the parsed input will be stored. For example:

int num;
double price;
char name[20];
scanf("%d %lf %s", &num, &price, name);

In this example, num, price, and name are variables where the parsed input will be stored. The %d, %lf, and %s specifiers in the format string correspond to the integer, floating-point number, and character array arguments, respectively.

Worked Example

Let's consider a simple example of using the scanf() function:

#include <stdio.h>

int main() {
int num;
double price;
char name[20];

printf("Enter your name: ");
scanf("%s", name);

printf("Hello, %s!\n", name);
printf("Enter your age (integer): ");
scanf("%d", &num);
printf("You are %d years old.\n", num);
printf("Enter the price of an item: ");
scanf("%lf", &price);
printf("The total cost is Rs. %.2f.", price * 10);

return 0;
}

In this example, we first ask the user to enter their name using scanf(). Then, we ask for their age and the price of an item, store the input in appropriate variables using &, and perform some calculations. Finally, we print a personalized message based on the input provided by the user.

Common Mistakes

  1. Forgetting to include the header file: Remember to include ` at the beginning of your program to use the scanf()` function.
  2. Not using the address-of operator (&): When passing arguments to the scanf() function, make sure to use the address-of operator (&) with variables to store the parsed input correctly.
  3. Ignoring whitespace in the format string: Whitespace characters in the format string are treated as literal spaces and can cause errors if not accounted for. For example: scanf("%s", name) will skip leading whitespace, while scanf(" %s", name) will ignore it.
  4. Not checking for input errors: The scanf() function may fail to read the expected data due to incorrect input or other issues. You can check for these errors using the feof() and ferror() functions.
  5. Incorrectly handling negative numbers: By default, the %d conversion specifier reads positive integers only. To handle negative numbers, you need to modify your code to read signed integers using %i.

Practice Questions

  1. Write a program that asks for the user's name, age, and favorite programming language and prints a personalized message based on the input.
  2. Write a program that reads three floating-point numbers and calculates their average.
  3. Write a program that reads an integer and checks if it is even or odd.
  4. Write a program that reads two strings and compares them lexicographically (alphabetically).
  5. Write a program that reads five integers and finds the maximum value among them.

FAQ

  1. Why do I need to use & with variables when using scanf()?
  • Using the address-of operator (&) with variables allows you to pass their addresses to the scanf() function, so that it can store the parsed input in the correct memory location.
  1. Why does my program skip leading whitespace when using scanf("%s", ...)?
  • By default, the %s conversion specifier skips leading whitespace characters (spaces, tabs, newlines) before reading a string. To read leading whitespace, you can use scanf(" %s", ...), where the space before the %s tells the function to consume any leading whitespace.
  1. How can I handle input errors with scanf()?
  • You can check for input errors using the feof() and ferror() functions. The feof() function returns a non-zero value when the end of the file is reached, while ferror() returns a non-zero value if an error occurred during the last read operation.
  1. Why do I get strange output when using scanf("%d", ...) with negative numbers?
  • By default, the %d conversion specifier reads positive integers only. To handle negative numbers, you need to modify your code to read signed integers using %i.
  1. What is the difference between scanf() and gets()?
  • The main difference between scanf() and gets() is that scanf() reads formatted input, while gets() reads a line of text until it encounters a newline character. Additionally, gets() is considered dangerous because it does not check for buffer overflows, which can lead to security vulnerabilities in your program. It is recommended to use scanf() instead of gets().