【发布时间】:2016-03-19 10:00:31
【问题描述】:
txt文件有1000个名字。
1 Jacob Sophia
2 Mason Emma
3 Ethan Isabella
4 Noah Olivia
5 William Ava
.....
程序总是说这个名字不在流行的男孩/女孩名字中。
经过调试,我意识到“排名”从未增加。它总是 1,我认为该程序只检查第一行。我再次运行程序并输入 Jacob。结果是一样的。我看不出我的错误在哪里。
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.
【问题讨论】:
-
您正在阅读
rank两次。无论如何,您的循环都会在一次迭代后退出。 -
我应该改变 while(ifs >> rank) 吗?
-
您应该检查 EOF(文件结尾)例如:
while (!ifs.eof()) -
我试过了。我只有在输入 Jacob 时才能获得良好的输出。 Jacob 是 #1,输出是 1 Jacob。但是当我输入 Mason(2#) 或任何名字时,我得到
不在流行的男孩名字中。
标签: c++