Dummy commit to test new ssh key
[eleutheria.git] / homework / scanfprob.c
blobebfd2f1aaccd432cd313477f5d621f79286c78e3
1 /*
2 * Compile with:
3 * gcc scanfprob.c -o scanfprob -Wall -W -Wextra -ansi -pedantic
4 */
6 #include <stdio.h>
7 #include <stdlib.h>
9 int main(void)
11 char buffer[100];
12 int a, rv;
15 * When scanf is attempting to convert numbers, any non-numeric characters
16 * it encounters terminate the conversion and are left in the input stream.
17 * Therefore, unexpected non-numeric input ``jams'' scanf again and again.
18 * E.g. Try to type a char and see what happens with the following code:
20 * do {
21 * printf("Input: ");
22 * scanf("%d", &a);
23 * } while (a != -1);
25 * See also: http://c-faq.com/stdio/scanfjam.html
28 /* First approach: check against the return value of scanf(3) */
29 do {
30 printf("Input: ");
31 rv = scanf("%d", &a);
32 if (rv == 0)
33 scanf("%[^\n]");
34 } while (a != -1);
36 /* Second approach: combine fgets(3) with sscanf(3) */
37 getchar(); /* Trim '\n' from previous */
38 do {
39 printf("Input: ");
40 fgets(buffer, sizeof buffer, stdin);
41 rv = sscanf(buffer, "%d", &a);
42 } while (rv == 0 || a != -1);
44 return EXIT_SUCCESS;