2013-10-08 147 views
0

我有一些代碼來比較不同的人回答的問題集,一個設置用戶輸入其他集來自.txt文件。當我運行它時,它給我一個超出範圍的斷言錯誤向量下標,我無法找到它來自哪裏。下面的代碼:矢量下標超出範圍錯誤

void compare() 
{ 
    const int qnum = 11; 
    string filename, temp; 
    string search[10] = {"1","2","3","4","5","6","7","8","9","0"}; 
    int answers[qnum], i, j, k, q= 0, numtemp = 0, pplNum; 
    ifstream infile; 
    vector <string> people; 
    vector <int> pplans; 
    vector <int> pplscore; 

    cout << "Please enter the name of the file you would like to enter: "; 
    cin >> filename; 

    string infilename= filename; 
    infile.open(infilename.c_str()); 

    //Temporary test part of the program until we add the GUI just copy another person's answer or put similar ones 
    //for testing purposes 


    infile >> pplNum; 
    //allows for all names and scores to fit in each vector 
    for(i = 0; i < pplNum; i++) 
    { 
     people.push_back(""); 
     people.push_back(""); 
     pplscore.push_back(0); 
    } 
    //takes the person's name 
      for(j = 0; !infile.eof(); j+ 2) 
     { 
      infile >> people[j]; 
      infile >> people[j+1]; 
     } 

     for(i = 0; i < pplNum; i++) 
     { 
      //sets the numbers for the individual in question 
      for(k = 0; k < qnum; k++) 
      { 
       infile >> pplans[k]; 
       if(answers[k] == pplans[k] && k < 10) 
        numtemp++; 
       else if (k == 10 && answers[k] == pplans[k]) 
        if(answers[answers[k]] == pplans[pplans[k]]) 
         numtemp++; 
      } 
      pplscore.push_back(0); 
      pplscore[i] = numtemp; 

     } 
} 
+3

我相信你的意思是在這裏寫'+ = 2':for(j = 0;!infile.eof() ; j + 2)' –

+1

txt文件中有什麼? (k = 0; k Beta

+0

用調試器運行你的程序(例如'gdb',如果你使用g ++),那麼你應該看到程序中哪一點出現斷言 – codeling

回答

0
vector <int> pplans; 
... 
infile >> pplNum; 
//allows for all names and scores to fit in each vector 
for(i = 0; i < pplNum; i++) 
{ 
    people.push_back(""); 
    people.push_back(""); 
    pplscore.push_back(0); 
} 
... 
for(i = 0; i < pplNum; i++) 
{ 
    //sets the numbers for the individual in question 
    for(k = 0; k < qnum; k++) 
    { 
    infile >> pplans[k]; 
    ... 
    } 
} 

你忘了,以騰出空間在pplans。 (最好使用push_back和實際數據,而不要依賴這樣的代碼。)

+0

所以我可以簡單地使用: pplans.push_back(infile中);? – TPOT94

+0

@ user2750772:不,對於(k = 0; k > N; pplans.push_back(N);}'。或者'int n;而(infile中>> n)的{pplans.push_back(N);}'。 – Beta