2013-05-19 13 views
-2

我已經開始學習C++,這讓我很頭疼。我寫了一個簡單的人「數據庫」應用程序,由於某種原因,在列出人員時失敗。C++應用程序失敗 - 沒有錯誤

string search; 
cout << "Give the name: "; 
cin >> search; 

vector<Person> foundPersons; 
for(vector<Person>::iterator it = persons.begin(); it != persons.end(); it++) { 
    Person p = *it; 

    if(search == p.getFirstname() || search == p.getSurname()) { 
     foundPersons.push_back(p); 
    } 
} 

if(!foundPersons.empty()) { 
    cout << "Found " << foundPersons.size() << " person(s).\n\n"; 
    cout << "Firstname\tSurname\t\tBirth year\n"; 
} else { 
    cout << "No matches."; 
} 

for(vector<Person>::iterator it = foundPersons.begin(); it != persons.end(); it++) { 
    Person p = *it; 
    cout << p.getFirstname() << "\t\t" << p.getSurname() << "\t" << p.getBirthYear() << "\n"; 
} 

cout << "\n"; 

personsvector<Person>的類型。我瀏覽所有條目,並將該名稱與給定的搜索值進行比較。如果找到,我將該人添加到foundPersons向量中。然後我打印No matches或發現的人數和表頭。接下來,我會瀏覽所有找到的人並將其打印到控制檯中。

如果我添加兩個人,例如「傑克例子」和「約翰例子」,我搜索「傑克」,它會找到「傑克」並打印它。但隨後程序停止。 Windows說「該程序已停止工作」。編譯期間或程序停止時不顯示錯誤。

怎麼了?

+5

總有一個理由。 – ChiefTwoPencils

+0

'人'是如何定義的? – chris

+1

我建議你通過一個調試器運行程序 - 至少應該指出程序停止的地方。 – DaveR

回答

12

你是for循環不太對,它看起來像你犯了一個錯字,並且引用了來自兩個不同列表的迭代器。變化:

for(vector<Person>::iterator it = foundPersons.begin(); it != persons.end(); it++) { 

for(vector<Person>::iterator it = foundPersons.begin(); it != foundPersons.end(); it++) { 
+8

+1令人驚歎的眼睛:) – Bill

+0

同樣的錯誤也是在第一'for'循環。 – Bill

+1

@開他的第一圈看起來對我很好。我在回答中引用了錯誤的循環來顯示錯誤的位置。 – Steve