2015-12-14 60 views
0

txt文件中有1000個名字。C++在txt文件中搜索行

1 Jacob Sophia 
2 Mason Emma 
3 Ethan Isabella 
4 Noah Olivia 
5 William  Ava 
..... 

程序總是說這個名字不在流行的男孩/女孩的名字中。

經過調試,我意識到「排名」從未增加。它總是1,我認爲這個程序只是檢查第一行。我再次運行程序並鍵入雅各布。結果是一樣的。我看不出我的錯誤在哪裏。

int main() 
{ 
    bool boyName = false; 
    bool girlName = false; 
    ifstream ifs; 
    int rank; 
    string boy_name, girl_name, name; 
    ifs.open("babynames2012.txt"); 

    if (ifs.fail()) 
     cout << "fail" << endl; 
    else 
     cout << "success" << endl; 


    cout << "Enter a name" << endl; 
    cin >> name; 


    while (ifs >> rank) 
    { 
     ifs >> rank >> boy_name >> girl_name; 
     if (name == boy_name) 
     { 
      cout << name << " is ranked " << rank << " among boy names" << endl; 
      boyName = true; 
     } 
     if (name == girl_name) 
     { 
      cout << name << " is ranked " << rank << " among girl names" << endl; 
      girlName = true; 
     } 

     if (boyName == false) 
     { 
      cout << name << " is not among the popular boy names" << endl; 
     } 
     if (girlName == false) 
     { 
      cout << name << " is not among the popular girl names" << endl; 
     } 

    } 
     ifs.close(); 
     system("pause"); 
     return 0; 
} 

結果總是在循環的中間同樣

<name> is not among the popular boy names. 
<name> is not among the popular girl names. 
+1

您正在閱讀'rank'兩次。無論如何,你的循環在一次迭代後退出。 –

+0

我應該改變(ifs >>等級)嗎? –

+0

你應該檢查EOF(文件結尾)ex:'while(!ifs.eof())' – Titus

回答

0

關閉ifs是不是一個好主意......

+0

哎。他們不應該在那裏。 修復了代碼 –