scanf("%d", &age);reads a number. The&passes the variable's address.scanf("%s", name);reads one word (it stops at a space).fgets(line, sizeof line, stdin);reads a whole line safely, including spaces.
C User Input
Read input with scanf and fgets.
✍️ 2 exercises in this lessonKey Takeaways: C User Input
Mastering C User Input helps you write clean and reliable C code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
C User Input Code Example
C#include <stdio.h>
#include <string.h>
int main() {
char name[50];
int age;
printf("Your full name: ");
fgets(name, sizeof name, stdin);
name[strcspn(name, "\n")] = '\0'; // remove the newline
printf("Your age: ");
scanf("%d", &age);
printf("Hello %s, next year you will be %d.\n", name, age + 1);
return 0;
}
Output
Your full name: Ali Khan Your age: 25 Hello Ali Khan, next year you will be 26.
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
C User Input Practice Exercises
Check what you learned in “C User Input”.
/ 2 solved
Fill in the blank
Read a number into age. Note the address-of operator.
scanf("%d", age);
✓ Correct!
Not quite. Try again.
Multiple choice
Which function safely reads a whole line including spaces?
✓ Correct!
Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services