即使出现错误,程序也会继续运行

时间:2017-04-14 15:29:31

标签: c arrays exit break eof

我有一个程序可以将文件中的某些数字检索到数组中。我遇到的最后一个问题是我的程序仍在运行,即使它无法打开文件,而不是结束它。即使程序结束,主菜单再次显示,但不显示任何数据

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.2f\n", avg);
            break;
    case 2: test_max_min(number_of_students, &max, &min, test);
            printf("\nMaximum score = %3d\n"
                      "Minimum score = %3d\n", 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.dat\n");
  else
  {
    while( fscanf(sp_input, "%d", &test[i])!=EOF)
    {
    i=i+1;
    ++*size;
    }
    fclose(sp_input);    // Close the stream
  }

  return 1;
}

1 个答案:

答案 0 :(得分:0)

是的,它一直在运行......

if (file_opened == 0)
{
  do
  {

表示如果文件已打开,则执行循环。你想要:

if (file_opened != 0)

另见有关其他错误的评论。