gpt4 book ai didi

C:从标准输入扫描

转载 作者:行者123 更新时间:2023-11-30 17:38:42 27 4
gpt4 key购买 nike

我正在编写代码,当从命令行调用时,该代码会重定向到文件。文件的行(通过标准输入发送)被解析和读取。我希望能够调用一个函数并让它扫描一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com