4
votes

I have a question about process that the scanf function takes when it encounters a non-whitespace character in the format string. According to the book I'm reading:

When a scanf function encounters a non-whitespace character in a format string, scanf compares it with the next input character. If the two characters match, scanf discards the input character and continues processing the format string. If the characters don't match, scanf puts the offending character back into the input, then aborts without further processing the format string or reading characters from the input.

I am a little confused. It says that scanf compares it with the next input character and if the two characters match, scanf discards the input character. Why do we say that it compares with the "next" input character?

Does this mean that if we have a format string like scanf("%d/%d", &x, &y) and the input 2/4, scanf compares with the four because it's the next input character from the /?

1
No, %d reads 2, the next input character is / and that gets compared with the / from your format string. Then %d reads 4.mch

1 Answers

3
votes

Another way of describing scanf is that for non-whitespace characters, it follows along the input with what it expects to see in the format string. However, if it finds a different reader, it "unreads" that character and then stops scanning altogether.

For example, let's look at:

int x, y;
int scanned = scanf("%dabc%d", &x, &y);

If we give it the input 10abc20, then it operates in this order:

  • It reaches %d, reads 10, and stores it in x.
  • One-by-one, it reads abc and follows along with the abc given in the format string.
  • It reaches %d, reads 20, and stores it in y.
  • It reaches the end of the format string, returning the value 2 for scanning two values.
  • Leaving the code, all characters from the input is consumed.

Giving the same program 10abz20 instead:

  • It reaches %d, reads 10, and stores it in x.
  • It reads ab correctly but when it reaches z, unreads that character, and returns early with the value 1, since it only scanned the first number.
  • Leaving the code, z20 is left unread and may be read later in the program.

So in your example scanf("%d/%d", &x, &y), the input 10/20 will scan completely, but 10d20 will only scan 10 into x and leave d20 unread. As an aside, 10/ 20 and 10/20 scans completely, but 10 /20 does not.