
User Input in C
? User Input in C
C allows you to take input from users using functions like scanf()
and fgets()
from the standard input (stdin
).
? Using scanf()
(most common)
#include <stdio.h>int main() { int age; printf("Enter your age: "); scanf("%d", &age); printf("You are %d years old.\n", age); return 0;}
? Format Specifiers:
Data Type | Format |
---|---|
int | %d |
float | %f |
char | %c |
string | %s |
?? For strings,
scanf("%s", str);
stops at the first whitespace.
? Example: Multiple Inputs
int a, b;scanf("%d %d", &a, &b);
? Reading Strings with Spaces ? Use fgets()
char name[50];printf("Enter full name: ");fgets(name, sizeof(name), stdin);printf("Hello, %s", name);
? Input a Character
char ch;scanf(" %c", &ch); // Note the space before %c to catch newline
? Pro Tips:
Always use
&
before variable names inscanf()
(except for strings).fgets()
is safer thanscanf("%s")
for reading full lines.