C User Input
1. Basic Input Functions
In C, user input is mainly taken using:
-
scanf()→ Reads formatted input -
getchar()→ Reads a single character -
gets()→ Reads a string (unsafe, avoid using) -
fgets()→ Reads a string safely
2. Using scanf()
-
scanf()is used for numbers, characters, and strings. -
Always provide address of the variable using
&for non-string types.
Syntax:
Example 1: Read an integer
Input/Output:
Example 2: Read a float
Input/Output:
Example 3: Read a character
Input/Output:
Tip: Space before
%cinscanfignores previous newline character.
Example 4: Read a string
Input/Output:
Note:
scanf("%s")cannot read strings with spaces.
3. Using fgets() for Strings with Spaces
Input/Output:
Use
strcspn(name, "\n")to remove the newline if needed:
4. Using getchar() to Read Single Character
Input/Output:
5. Key Points About User Input
-
Use
scanffor formatted input (numbers, strings without spaces, chars). -
Use
fgetsfor strings with spaces. -
Use
getcharfor single characters. -
Always check array size for strings to avoid buffer overflow.
-
Use
&with variables except strings, because strings are already pointers.
