5 min read
Reading User Input
Prerequisites: Strings
scanf reads formatted input; fgets reads a whole line safely,
including spaces:
int age;
printf("How old are you? ");
scanf("%d", &age);
char name[50];
printf("What's your name? ");
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0'; // strip the trailing newline
printf("Hello, %s! You are %d.\n", name, age);
Common mistakes
- Forgetting the
&before a variable inscanf—scanfneeds the variable's address to write into, not its value. - Using
scanf("%s", name)for a full name with spaces —%sstops at the first space.fgetsreads the entire line instead. - Not checking
scanf's return value — it returns how many items it successfully matched, which is worth checking before trusting the result.