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?
- A. while (scanf("%d", &x) != EOF) { ... }
- B. while (!feof(stdin)) { scanf("%d", &x); ... }
- C. while (getchar() != EOF) { scanf("%d", &x); ... }
- 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
- A character loop reads bytes with char c = getchar() and tests while (c != EOF). Why can this loop be wrong?
- To count occurrences of values up to 10^6 in O(n), which code is correct and fast enough?
- A recursive depth-first search could recurse 10^6 levels deep on a path-shaped graph. Which approach is correct and safe?
- A string of up to 10^6 characters is read with fgets. Which buffer declaration is correct?
- A loop walks a string with for (i = 0; i < strlen(s); i++) on a string of length 10^6. What is the total cost?
- A binary search on the answer in [1, 10^18] computes mid = (lo + hi) / 2 with long long. Is this safe?