ProgrammingHard

A scanf loop reads integers until the end of input. Which loop is correct when the input may end with a non-numeric token?

  1. A. while (scanf("%d", &x) != EOF) { ... }
  2. B. while (!feof(stdin)) { scanf("%d", &x); ... }
  3. C. while (getchar() != EOF) { scanf("%d", &x); ... }
  4. D. while (scanf("%d", &x) == 1) { ... }

Correct answer: D. while (scanf("%d", &x) == 1) { ... }

scanf returns the number of items converted. A non-numeric token gives 0, which stops this loop, while the EOF test would spin forever on that token.

More C Programming questions

Exams that ask this topic