C User Input

C Tutorial

 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 TypeFormat
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()

Featurescanffgets
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() before fgets()

 Command-Line Input (Advanced)

  •  Used in system programs

 Common Mistakes

  •  Forgetting & in scanf() 
  •  Using wrong format specifier
  •  Mixing scanf() and fgets() incorrectly
  •  Using gets()

 Interview Questions (Must Prepare)

  1. Difference between scanf() and fgets()

  2. Why & is used in scanf()?

  3. Why %lf for double?

  4. Why gets() is unsafe?

  5. 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 limited
  • fgets() is safer for strings
  •  Correct format specifiers are critical
  •  Avoid unsafe functions
  •  Very important for interviews & projects

You may also like...