代码之家  ›  专栏  ›  技术社区  ›  Dervin Thunk

当扫描!=eof或scanf==1?

  •  10
  • Dervin Thunk  · 技术社区  · 15 年前

    其他部分 (格式良好的数据、良好的缓冲实践以及其他),是否有原因使我更喜欢循环而返回 scanf 是1,而不是 !EOF ?我可能在某个地方读过这个,或者别的什么,但我也可能弄错了。其他人怎么想?

    3 回复  |  直到 14 年前
        1
  •  14
  •   Brian Webster Jason    14 年前

    scanf 返回成功转换的项数…或EOF出错。所以用它的意义来编码条件。

    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 */
    

    人为的例子

    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 */;
    

    编辑:添加了另一个更人为的示例

    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;
    }
    
        2
  •  1
  •   Steve Jessop    15 年前

    取决于您想如何处理格式错误的输入-如果扫描模式不匹配,您可以 0 返回。因此,如果您在循环之外处理这种情况(例如,如果您将其视为输入错误),那么将其与 1 (或者您的scanf调用中有多少项)。

        3
  •  0
  •   Mark Ransom    15 年前

    http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

    一旦成功,函数将返回 成功读取的项目数。这个 计数可以匹配预期的 读数或更少,甚至是零,如果 匹配失败。在这种情况下 任何数据之前的输入失败 可以成功读取,EOF为 返回。

    唯一能确保您读取预期项目数的方法是将返回值与该数字进行比较。