2015-10-24 75 views
0

該程序應該打開.csv文件並將數據輸入到矢量中。後來我應該實現一個優先隊列。但是,當我嘗試運行它時遇到此錯誤。C++矢量下標超出範圍錯誤

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <vector> 
#include "Prisoner.h" 
#include "Jailed.h" 
using namespace std; 

int main() 
{ 

string line, ID, sentenceIn, servedIn, lastName, firstName; 
int sentence, served; 

vector<string> idNum; 
vector<int> sentenceLen; 
vector<int> servedTime; 
vector<string> lastNameIn; 
vector<string> firstNameIn; 


ifstream data("prisoner_data.csv"); 

if (!data.is_open()) 
{ 
    exit(EXIT_FAILURE); 
} 

while (getline(data, line)) 
{ 

    getline(data, ID, ','); 
    cout << ID << " "; 
    idNum.push_back(ID); 

    getline(data, sentenceIn, ','); 
    cout << sentenceIn << " "; 
    istringstream(sentenceIn) >> sentence; 
    sentenceLen.push_back(sentence); 


    getline(data, servedIn, ','); 
    cout << servedIn << " "; 
    istringstream(servedIn) >> served; 
    servedTime.push_back(served); 


    getline(data, lastName, ','); 
    lastNameIn.push_back(lastName); 
    cout << lastName << " "; 

    getline(data, firstName, ','); 
    firstNameIn.push_back(firstName); 
    cout << firstName << " "; 
} 
Prisoner p[100]; // Initializing Prisoner class 

for (int i = 0; i <= idNum.size(); i++) 
{ 
    p[i].setIdNum(idNum[i]); 
    p[i].setSentence(sentenceLen[i]); 
    p[i].setTimeServed(servedTime[i]); 
    p[i].setLastName(lastNameIn[i]); 
    p[i].setFirstName(firstNameIn[i]); 
} 

data.close(); 
system("pause"); 
return 0; 

}

我還可以包括囚犯類,如果需要弄清楚的問題。

回答

2
for (int i = 0; i <= idNum.size(); i++) 

應該

for (int i = 0; i < idNum.size(); i++) 
+0

可能?當然。 – Barmar

+0

@Barmar目前還不清楚'idNum.size()'是如何與100相關的;)但我的猜測是它等於囚犯的數量。 – vsoftco

+0

'100'與它有什麼關係?這個錯誤大概是關於'idNum [i]'而不是'p [i]'。 C++不會爲普通數組進行邊界檢查,只有類似'vector' – Barmar