Skip to content
AgileLogics
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 in scanf — scanf needs the variable's address to write into, not its value.
  • Using scanf("%s", name) for a full name with spaces — %s stops at the first space. fgets reads 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.