While scanf!=EOF or scanf==1?

前端 未结 3 488
故里飘歌
故里飘歌 2021-01-02 06:54

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

3条回答
  •  执念已碎
    2021-01-02 07:23

    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;
    }
    

提交回复
热议问题