Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While scanf!=EOF or scanf==1?

Tags:

c

scanf

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?

like image 656
Dervin Thunk Avatar asked Nov 11 '10 22:11

Dervin Thunk


People also ask

Does scanf detect EOF?

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.

What does scanf 1 mean?

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.

How do you know if input is EOF?

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 is EOF programming?

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.


2 Answers

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;
}
like image 106
pmg Avatar answered Sep 17 '22 15:09

pmg


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).

like image 45
Steve Jessop Avatar answered Sep 21 '22 15:09

Steve Jessop