0
0
CHow-ToBeginner · 3 min read

How to Use scanf in C: Syntax, Example, and Tips

In C, use scanf to read formatted input from the user by specifying a format string and pointers to variables where the input will be stored. For example, scanf("%d", &num); reads an integer into the variable num. Always pass the address of the variable using & except for strings.
📐

Syntax

The basic syntax of scanf is:

  • scanf("format_specifiers", &variable1, &variable2, ...);
  • format_specifiers: A string that tells scanf what type of data to read, like %d for integers, %f for floats, or %s for strings.
  • &variable: The address of the variable where the input will be stored. Use the & operator to pass the address, except for strings where the array name acts as the address.
c
scanf("%d", &num);
💻

Example

This example shows how to use scanf to read an integer and a float from the user and then print them.

c
#include <stdio.h>

int main() {
    int age;
    float height;

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

    printf("Enter your height in meters: ");
    scanf("%f", &height);

    printf("You are %d years old and %.2f meters tall.\n", age, height);
    return 0;
}
Output
Enter your age: 25 Enter your height in meters: 1.75 You are 25 years old and 1.75 meters tall.
⚠️

Common Pitfalls

  • Forgetting to use & before variables causes errors because scanf needs the address to store input.
  • Using wrong format specifiers leads to incorrect input reading or runtime errors.
  • Reading strings without specifying a maximum length can cause buffer overflow.
  • scanf leaves the newline character in the input buffer, which can affect subsequent input calls.
c
#include <stdio.h>

int main() {
    int num;

    // Wrong: missing &
    // scanf("%d", num); // This causes a runtime error

    // Correct:
    scanf("%d", &num);

    return 0;
}
📊

Quick Reference

Format SpecifierData TypeDescription
%dintReads an integer
%ffloatReads a floating-point number
%lfdoubleReads a double precision float
%ccharReads a single character
%schar arrayReads a string (no spaces)

Key Takeaways

Always use the & operator before variables in scanf except for strings.
Match format specifiers to the variable types to avoid errors.
Be careful with string input to prevent buffer overflow.
scanf reads input until it matches the format, leaving newline characters in the buffer.
Test input carefully to handle unexpected user input.