Ceteris paribus (well formed data, good buffering practices and what not), is there a reason why I prefer to loop while the return of scanf
is 1, rather than !EOF
? I may have read this somewhere, or whatever, but I may have it wrong as well. What do other people think?
scanf returns EOF if end of file (or an input error) occurs before any values are stored. If any values are stored, it returns the number of items stored; that is, it returns the number of times a value is assigned by one of the scanf argument pointers.
scanf returns the number of items successfully scanned. – Johnny Mopp. Mar 13, 2020 at 17:47. 10. The == 1 is necessary because scanf can return EOF which will be implicitly considered true , but no value for number has been read.
The function feof() is used to check the end of file after EOF. It tests the end of file indicator. It returns non-zero value if successful otherwise, zero.
What Does End Of File (EOF) Mean? End Of File or EOF is a specific designation for a file marker that indicates the end of a file or data set.
scanf
returns the number of items succesfully converted ... or EOF on error. So code the condition the way it makes sense.
scanfresult = scanf(...);
while (scanfresult != EOF) /* while scanf didn't error */
while (scanfresult == 1) /* while scanf performed 1 assignment */
while (scanfresult > 2) /* while scanf performed 3 or more assignments */
Contrived example
scanfresult = scanf("%d", &a);
/* type "forty two" */
if (scanfresult != EOF) /* not scanf error; runs, but `a` hasn't been assigned */;
if (scanfresult != 1) /* `a` hasn't been assigned */;
Edit: added another more contrived example
int a[5], b[5];
printf("Enter up to 5 pairs of numbers\n");
scanfresult = scanf("%d%d%d%d%d%d%d%d%d%d", a+0,b+0,a+1,b+1,a+2,b+2,a+3,b+3,a+4,b+4);
switch (scanfresult) {
case EOF: assert(0 && "this didn't happen"); break;
case 1: case 3: case 5: case 7: case 9:
printf("I said **pairs of numbers**\n");
break;
case 0:
printf("What am I supposed to do with no numbers?\n");
break;
default:
pairs = scanfresult / 2;
dealwithpairs(a, b, pairs);
break;
}
Depends what you want to do with malformed input - if your scan pattern isn't matched, you can get 0
returned. So if you handle that case outside the loop (for example if you treat it the same as an input error), then compare with 1
(or however many items there are in your scanf call).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With