#include <stdio.h>
int main(int argc, const char *argv[]) {
FILE *fp = fopen("input.txt", "r");
char buffer[256];
int n, a, b;
n = a = b = 0;
while (fgets(buffer, 250, fp)) {
n = sscanf(buffer, "%d %d", &a, &b);
printf("%d %d %d\n", a, b, n);
}
fclose(fp);
printf("Next Part\n");
fp = fopen("input.txt", "r");
n = a = b = 0;
while (0 < (n = fscanf(fp, "%d %d", &a, &b))){
printf("%d %d %d\n", a, b, n);
}
return 0;
}
input.txt contains these lines:
1 2 3
4 abc 5 6
7 8
the 1 next 2 line 3 is blank
4 5 the above line is blank 6
7 8
I know the first printed line will be 1 2 2 because n was set to the return value of sscanf (which returned 2 since both integers were read I assume). I, however, am unsure of what the second line would produce? If I can get someone to work out and explain the second line for me, I would appreciate it. I am also confused on what will happen when the loop experiences a blank line?
Admittedly the
sscanfdocumentation is tedious to read.This small example shows what happens if the input does not match the format string.
The output is:
During the first
sscanf, 2 items have been read as1and2match the%d %dformat string.During the second
sscanf, only 1 item has been read as only11matches the first%d, butfoodoes not match the second%d.bis not modified.It let you figure out what
sscanfdoes if you feed it a blank line. Hint: it's not totally obvious, but it's in the documentation.