【发布时间】: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....”,而不会停止通过标准输入接受更多输入。是扫描到选择变量有问题吗?
【问题讨论】: