我希望能夠循環打開和關閉文件以不斷搜索名稱。更適合從文件中循環輸入的方法?
第一次沒問題,輸出是預期的,那麼當選擇y時,會出現輸出循環。
任何想法爲什麼會發生這種情況?邏輯似乎不僅僅是正確的。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string boys, girls, name;
int rank;
char end = 'n';
while (end != 'y' || end != 'Y')
{
cout << "Enter a name to search";
cin >> name;
ifstream input;
input.open("Names2016");
if (input.fail())
cout << "Failed to open file.\n";
while (!input.eof())
{
input >> rank >> boys >> girls;
if (boys == name)
cout << name << " ranks " << rank << " among boys.\n";
if (girls == name)
cout << name << " ranks " << rank << " among girls.\n";
}
input.close();
cout << "Would you like to search another name?\n"
<< "Enter Y for yes or N for no.\n";
cin >> end;
}
return 0;
}
http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong使用。 –
我們能否看到您的Names2016文件? – Tyger
我很新,不確定如何向您顯示文件。它由一個等級,一個空間,與該等級相關聯的男孩名字,一個空間以及與該等級相關聯的女孩名字組成,然後進入新的行。我從https://www.ssa.gov/cgi-bin/popularnames.cgi中提取信息,但您必須將格式調整爲1000個名稱。我非常抱歉,我不知道如何給你確切的文件 – NewToThis