HOME HTML EDITOR C JAVA PHP

C User Input: Making Programs Interactive

To create programs that truly provide value, we need to allow users to interact with them. In C, the most common way to get user input is by using the scanf() function. However, depending on whether you are reading numbers, single characters, or full sentences, there are different methods you should use.

1. Using the scanf() Function

The scanf() function is used to take input from the standard input (usually the keyboard). It requires two things: a **format specifier** (to know what type of data to expect) and an **address operator** (&) to tell C where to store that data in memory.

Basic Example: Reading an Integer

#include <stdio.h>

int main() {
    int myAge;
    printf("Enter your age: ");
    
    // Use %d for integers and & to point to the variable
    scanf("%d", &myAge);
    
    printf("Your age is: %d", myAge);
    return 0;
}

2. Multiple Inputs at Once

The scanf() function allows you to accept multiple inputs in a single line. You simply list the format specifiers and provide the corresponding variable addresses.

int age;
char grade;
printf("Enter age and grade: ");
scanf("%d %c", &age, &grade);

3. Taking String Input (and its limitations)

When taking a string as input, you use the %s format specifier. **Crucially**, you do not need the & operator for strings because a string's name already represents its memory address.

char firstName[30];
printf("Enter your first name: ");
scanf("%s", firstName);
printf("Hello %s", firstName);
[Image showing how scanf stops reading a string at the first whitespace]
Warning: The scanf() function stops reading as soon as it encounters a whitespace (space, tab, or newline). If you type "John Doe", scanf() will only store "John".

4. Reading a Full Line of Text

To read a string that contains spaces (like a full name or a sentence), the fgets() function is the preferred choice. It is safer than scanf() because it prevents "buffer overflow" by allowing you to specify the maximum number of characters to read.

char fullName[50];
printf("Enter your full name: ");

// fgets(variable, size, stdin)
fgets(fullName, sizeof(fullName), stdin);

printf("Name: %s", fullName);

5. Format Specifiers Reference

Using the correct specifier is mandatory. If you use %d for a float, your program will produce incorrect results or crash.

Data Type Format Specifier
Integer %d
Float (Decimal) %f
Character %c
String (Words) %s

6. Common Pitfalls for Beginners

Pro Tip: For robust software, always validate user input. In 2026, user input is considered a major security vector; never trust that a user will type an integer just because you asked for one!