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, rathe
From http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
On success, the function returns the number of items succesfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.
The only way to be sure that you read the number of items intended is to compare the return value to that number.
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).
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;
}