【问题标题】:C: Scanning from stdinC:从标准输入扫描
【发布时间】:2014-02-27 03:53:44
【问题描述】:

我正在编写从命令行调用时重定向文件的代码。文件的行(通过标准输入发送)被解析和读取。我希望能够调用一个函数并让它扫描一个 int,但似乎 scanf 中的残留数据存在问题(我实际上不知道这是否是问题,但这就是我能想到的全部)。这是我的代码:

dataSetAnalysis(data, experiments);
int selection;
while(1){ //always true. The loop only breaks when the user inputs 4.
    printf("DATA SET ANALYSIS\n"
           "1. Show all the data.\n"
           "2. Calculate the average for an experiment.\n
           "3. Calculate the average across all experiments.\n
           "4. Quit.\n"
           "Selection:__");
    switch(selection){
    case 1:
        displayAll(d,e);
        break;
    case 2:
        individualAverage(d,e);
        break;
    case 3:
        allAverage(d);
        break;
    case 4:
        exit(0);
    }
    scanf("%d", &selection);
}

这是主要方法的后半部分。

while(fgets(currentLine, 20, ifp) != NULL){ //while there is still data in stdin to be read

    experiments[i] = currentLine; //experiment[i] points to the same value as current line. Each value in experiments[] should contain pointers to different positions in the allocated buffer array.
    currentLine += 20; //currentLine points 20 characters forward in the buffer array.

    int j = 0; //counter for the inner while loop

    while(j<10){ //while j is less than 10. We know that there are 10 data points for each experiment
        scanf("%d ", &intBuffer[j]);
        data[i][j] = intBuffer[j];
        j++;
    }

    numExperiments++; //each path through this loop represents one experiment. Here we increment its value.
    i++;
}

当到达 dataSetAnalysis() 中的 while 循环时,程序无限循环并继续打印“DATA SET ANALYSIS....”,而不会停止通过标准输入接受更多输入。是扫描到选择变量有问题吗?

【问题讨论】:

    标签: c stdin scanf


    【解决方案1】:

    问题是你的标准输入不清晰,你必须通过迭代来清除你的输入缓冲区,直到你找到一个 '\n' 或输入命中。

    试试这个

    while('\n' != getchar()) { }

    就在你 scanf 之前,它会摆脱无限循环

    类似

    while('\n' != getchar()) {} scanf("%d", selection);

    【讨论】:

      【解决方案2】:

      第一个基本规则是“始终检查输入函数的返回值”(例如scanf())。它们总是返回一些指示它们是否成功,如果它们不成功,则不应使用函数调用成功时设置的值。

      对于scanf() 等,使用该函数的正确方法是测试您是否获得了预期的转换值数量:

      if (scanf("%d", &intBuffer[j]) != 1)
         …handle error…
      

      代码中还有格式字符串:"%d "。直到您在数字后键入一个非空白字符,这才停止。这很令人困惑,但格式字符串中的任何空格(空格、制表符、换行符)都意味着读取可选空格,但该函数仅在输入非空格字符时才知道何时完成读取空格。

      【讨论】:

      • 好的,所以我使用空格 b/c 输入格式化为空格,如下所示:
      • 但是您是说 scanf 没有按应有的方式工作,返回值会暗示这一点吗?这部分代码似乎运行良好。
      • 您不需要空格,因为%d 会跳过前导空格。事实上,除了%c 和%[…] 之外的所有转换规范都会跳过前导空格。我不清楚代码是如何工作的,但如果你正在输入程序的输入(而不是从文件重定向,比如说),那么"%d " 格式后面的空格不会停止阅读直到您键入除空格以外的其他内容。因此,在阅读了9 之后,它会等到您输入除空白、制表符或换行符之外的其他内容,然后再返回您的程序。
      • 好的,扫描没有空间。但这并不能解决在dataSetAnalysis()中执行while循环时程序从不停止扫描的问题。这两个问题是否相关?
      • 请研究如何创建 MCTRE How to create a Minimal, Complete, Tested and Readable example 或 SSCCE (Short, Self-Contained, Correct Example)。我不知道在哪里发生了什么。
      猜你喜欢
      • 2021-09-09
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      相关资源
      最近更新 更多