🎓 A1Learner
🔍
0 of 50 lessons completed

C scanf Traps

A scanf trap is a place where scanf reads something other than what was typed. The last lesson read numbers and text with scanf; this lesson shows the three places where that reading goes wrong.

The leftover newline

The program reads 25, then reads one char. That char is the leftover newline, so the print shows 10, the value of the newline.

#include <stdio.h>

int main() {
  int age = 0;
  char letter = '?';
  scanf("%d", &age);
  scanf("%c", &letter);
  printf("%d\n", letter);
  return 0;
}

Stopping at a space

The program reads one word from "Ada Lovelace". %s stops at the space, so only Ada reaches the print line.

#include <stdio.h>

int main() {
  char word[20] = {0};
  scanf("%s", word);
  printf("%s\n", word);
  return 0;
}

A width limit

The program reads at most five letters from Christopher. Only Chris reaches the print line.

#include <stdio.h>

int main() {
  char word[20] = {0};
  scanf("%5s", word);
  printf("%s\n", word);
  return 0;
}

Example

#include <stdio.h>

int main() {
  int age = 0;
  char letter = '?';
  scanf("%d", &age);
  scanf(" %c", &letter);
  printf("%c\n", letter);
  return 0;
}

Key points

  • After scanf reads a number, the Enter key press stays behind in the line.
  • A %c straight after a %d reads that leftover newline, not the next letter.
  • The leftover newline has the value 10, so printing it as a number shows 10.
  • A space before %c, as in " %c", skips the leftover newline.
  • %s stops at the first space, so it reads one word and no more.
  • A width such as %5s reads at most five letters from a longer word.

scanf reads 25 into age. The next scanf uses " %c", and the space skips the leftover newline. The print line shows A, the letter that was typed.

Note

Without a width, %s keeps reading past the end of the row.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does %s read from "Ada Lovelace"?