我的程序中出现了访问冲突(分段错误)?

时间:2013-04-28 21:37:43

标签: c++ if-statement crash while-loop counter

这个程序对我来说非常头疼。无论出于何种原因,一旦到达“学生3”,它就会崩溃。我找不到任何陷入其中的无限循环或其他任何原因导致它崩溃。任何帮助都非常感激。

#include <iostream>
#include <string>
using namespace std;

int main()
{
 const int ARRAY_SIZE = 5;
 const int ARRAY_SIZE_TWO = 4;
 const int ARRAY_SIZE_THREE = 20;
 string names[ARRAY_SIZE];
 double grades[ARRAY_SIZE];
 double average[ARRAY_SIZE];
 double averageFinal[ARRAY_SIZE];
 string letter[ARRAY_SIZE] = {"A", "B", "C", "D", "F"};
 string studentLetter[ARRAY_SIZE]; 
 int counterOne = 0;
 int counterTwo = 0;
 int counterThree = 0;
 double temp;
 while (counterOne < ARRAY_SIZE)
 {
  system("CLS");
  cout<<"Enter the name of student number " <<(counterOne + 1) <<":"<<endl;
  cin>>names[counterOne];
  while(counterTwo < ARRAY_SIZE_TWO)
  {
   system("CLS");
   cout<<"Enter the test scores for " <<names[counterOne] <<":" <<endl;
   cout<<"Enter test score number " <<(counterTwo + 1) <<" for " <<names[counterOne] <<":" <<endl;
   cin>>grades[counterThree];
   counterTwo += 1;
   counterThree += 1;
   average[counterOne] += grades[counterThree];
  }
  counterTwo = 0;
  counterOne += 1;
 }
 counterOne = 0;
 counterTwo = 0;
 counterThree = 0;
 while(counterOne < ARRAY_SIZE)
 {
  averageFinal[counterOne] = average[counterOne] / 12;
  if (averageFinal[counterOne] < 89)
  {
   studentLetter[counterOne] = letter[0];
  }
  else if (averageFinal[counterOne] < 79)
  {
   studentLetter[counterOne] = letter[1];
  }
  else if (averageFinal[counterOne] < 69)
  {
   studentLetter[counterOne] = letter[2];
  }
  else if (averageFinal[counterOne] < 59)
  {
   studentLetter[counterOne] = letter[3];
  }
  else
  {
   studentLetter[counterOne] = letter[4];
  }
  counterOne += 1;
 }

 while(counterTwo < ARRAY_SIZE)
 {
  cout<<names[counterTwo] <<":" <<endl <<"Average: " <<averageFinal <<"%" <<endl <<"Letter Grade: " <<studentLetter[counterTwo] <<endl;
  counterTwo += 1;
 }
 system("PAUSE");
 return 0;
}

1 个答案:

答案 0 :(得分:2)

正如vidit指出的那样,counterThree允许在读取循环中溢出ARRAY_SIZE。您需要重置它,或稍后使用其他计数器。一个好的做法是保持变量范围尽可能窄,而不是重复使用变量(避免“临时”),这可能导致簿记混乱。