C:从标准输入扫描

标签 c stdin scanf

我正在编写代码,当从命令行调用时,该代码会重定向到文件。文件的行(通过标准输入发送)被解析和读取。我希望能够调用一个函数并让它扫描一个 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....”,而不会停止通过标准输入接受更多输入。扫描到选择变量有问题吗?

最佳答案

问题是您的标准输入不明确,您必须通过迭代来清除输入缓冲区,直到找到“\n”或输入命中。

尝试使用这个

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

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

类似的东西

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

关于C:从标准输入扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22058690/

相关文章:

c - 你什么时候使用 uint_least16_t

c++ - 在Windows下杀死所有未列入白名单的进程

c - 如何调试使用 gdb 中辅助 txt 文件输入的程序?

node.js - 从标准输入读取时无法使用 CTRL D 触发 'end' 事件

python - 捕获交互式 Python shell 输出和输入

c - 使用 C 中的 scanf 函数获取数组的值

c++ - Fscanf 未从文件的最后一行读取预期值 (C/C++)

c - 在 C 中,空字符和换行符有什么区别?

c - c中的表达式

c - 使用按位 C