C User Input

C User Input (Beginner → Advanced)
User input in C language allows a program to accept data from the user at runtime.
C provides several input functions via the standard I/O library <stdio.h>.
Why User Input Is Important?
- Makes programs interactive
- Allows dynamic data processing
- Essential for real-world applications
- Frequently asked in interviews
Most Common User Input Function: scanf()
Syntax
Example
&(address-of) is required for variables (except arrays)
Taking Multiple Inputs Using scanf()
Taking Character Input
Using scanf()
Using getchar()
- Reads a single character
Taking String Input
Using scanf() (Stops at space)
Using fgets() (Recommended)
- Reads full line (including spaces)
Reading Integer, Float & Double
| Data Type | Format |
|---|---|
| int | %d |
| float | %f |
| double | %lf |
| char | %c |
| string | %s |
Using gets() (Do NOT Use)
- Causes buffer overflow
- Removed from modern C standards
Using scanf() vs fgets()
| Feature | scanf | fgets |
|---|---|---|
| Reads spaces | No | Yes |
| Buffer safe | No | Yes |
| Recommended | Limited | Yes |
User Input with Arrays
- Common in DSA problems
User Input with Structures
Clear Input Buffer (Common Issue)
- Used after
scanf()beforefgets()
Command-Line Input (Advanced)
- Used in system programs
Common Mistakes
- Forgetting
&inscanf() Using wrong format specifier- Mixing
scanf()andfgets()incorrectly - Using
gets()
Interview Questions (Must Prepare)
Difference between
scanf()andfgets()Why
&is used inscanf()?Why
%lffor double?Why
gets()is unsafe?How to read a full line with spaces?
Real-Life Use Cases
Form input handling
Configuration reading
Competitive programming
Embedded systems
CLI tools
Summary
scanf()is commonly used but limitedfgets()is safer for strings- Correct format specifiers are critical
- Avoid unsafe functions
- Very important for interviews & projects
