我有一个程序可以将文件中的一些数字检索到数组中。我遇到的最后一个问题是我的程序即使无法打开文件,也会继续运行,而不是结束它。即使它说程序结束,main的菜单也会再次出现,但不显示任何数据
int main (void)
{
int choice, max, min;
float avg;
int test[MAX_NUMBER_OF_STUDENTS];
int file_opened;
int number_of_students;
file_opened = get_test_scores(test, &number_of_students);
if (file_opened == 0)
{
do
{
choice = menu();
switch (choice)
{
case 0: printf("nProgram is over.n");
break;
case 1: test_avg(&avg, test, number_of_students);
printf("nAverage score on test = %5.2fn", avg);
break;
case 2: test_max_min(number_of_students, &max, &min, test);
printf("nMaximum score = %3dn"
"Minimum score = %3dn", max, min);
break;
case 3: print_test(test,number_of_students);
break;
default:
printf("This should never happen!");
}
} while (choice != 0);
}
return 0;
}
int get_test_scores(int test[], int* size)
{
FILE* sp_input; // Pointer to the input stream (from a file)
int i;
sp_input = fopen("a20.dat", "r");
if (sp_input == NULL)
printf("nUnable to open the file a20.datn");
else
{
while( fscanf(sp_input, "%d", &test[i])!=EOF)
{
i=i+1;
++*size;
}
fclose(sp_input); // Close the stream
}
return 1;
}
是的,它一直在运行...
if (file_opened == 0)
{
do
{
表示如果文件尚未打开,则执行循环。你想要:
if (file_opened != 0)
另请参阅有关其他错误的评论。