How to Take User Input in C

In C, we use the scanf() function to read input from the user. Just like printf() prints to the screen, scanf() gets data from the keyboard.


✏️ Example: Ask the User for Their Age

#include <stdio.h>

int main() {
    int age;

    printf("Enter your age: ");     // Ask the user
    scanf("%d", &age);              // Read an integer and store it in 'age'

    printf("You are %d years old.\n", age);

    return 0;
}

πŸ” Explanation:

LineWhat It Does
int age;Declares a variable age to store an integer.
printf("Enter your age: ");Prints a message asking the user for their age.
scanf("%d", &age);Reads an integer from the user and stores it in age.
&ageThe & means β€œaddress of” β†’ tells scanf where to store the input.
printf("You are %d years old.\n", age);Prints the age back to the user.

πŸ›  Example: Ask for Name and Age

#include <stdio.h>

int main() {
    char name[50];    // A string (array of characters)
    int age;

    printf("Enter your name: ");
    scanf("%s", name);      // Read a word (no spaces)

    printf("Enter your age: ");
    scanf("%d", &age);      // Read an integer

    printf("Hello, %s! You are %d years old.\n", name, age);

    return 0;
}

Important Notes:

  • scanf("%s", name); β†’ Reads a word (up to the first space). To read full sentences (with spaces), more advanced functions like fgets() are used.
  • Buffer size: char name[50]; means we can store up to 49 characters + 1 for the string terminator ('\0').

πŸ”— Common Format Specifiers in scanf:

SpecifierData TypeExample
%dInteger (int)scanf("%d", &num);
%fFloat (float)scanf("%f", &num);
%lfDouble (double)scanf("%lf", &num);
%cCharacter (char)scanf(" %c", &letter);
%sString (array of char)scanf("%s", name);

Tip: Notice a space before %c in scanf(" %c", &letter); β†’ This skips leftover newline characters from previous input.


βœ… Conclusion

  • scanf() lets your program interact with the user.
  • Always match the format specifier to the data type.
  • Don’t forget the & (address-of) for most variables (but not for strings).

πŸ’‘ Next challenge idea: Create a program that asks for two numbers and prints their sum!

Feedback Display

Learner Reviews