0
0
CHow-ToBeginner · 3 min read

How to Take Input from User in C: Simple Guide

In C, you take input from the user using the scanf function, which reads formatted data from the keyboard. You provide a format specifier like %d for integers or %s for strings, and pass the address of the variable where the input will be stored.
📐

Syntax

The basic syntax to take input in C is:

scanf("%format_specifier", &variable);

Here:

  • %format_specifier tells scanf what type of data to expect (e.g., %d for int, %f for float, %c for char, %s for string).
  • &variable is the address of the variable where the input will be stored. The & symbol means "address of".
c
scanf("%d", &number);
💻

Example

This example shows how to take an integer input from the user and print it back:

c
#include <stdio.h>

int main() {
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    printf("You entered: %d\n", number);
    return 0;
}
Output
Enter a number: 42 You entered: 42
⚠️

Common Pitfalls

  • Forgetting the & before the variable name causes errors because scanf needs the variable's address.
  • Using wrong format specifiers leads to incorrect input reading or program crashes.
  • Reading strings with %s stops at the first space, so it cannot read multi-word inputs.
  • Not checking the return value of scanf can hide input errors.
c
#include <stdio.h>

int main() {
    int number;
    // Wrong: missing &
    // scanf("%d", number); // This will cause a compile error or crash

    // Correct:
    scanf("%d", &number);
    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

Use scanf with the correct format specifier and the address of the variable to read user input.
Always include the & operator before variables except for arrays when using scanf.
Check the format specifier matches the variable type to avoid errors.
Remember that %s reads only up to the first space; use other methods for full lines.
Common mistakes include missing & and wrong format specifiers.