我目前正在用C ++编写一个菜单驱动程序,但在Output文件中搜索某个int有点困难。我的功能看起来像这样。
int studentId;
int searchId;
double examGrade1, examGrade2, examGrade3;
ifstream readGrades;
do
{
cout << "Enter the student ID: ";
cin >> searchId;
if (searchId < 0 || searchId > 9999) {
cout << "Your student ID must be in between 0 and 9999! Try again...\n";
}
} while (searchId < 0 || searchId > 9999);
readGrades.open("grades.txt");
if (readGrades)
{
system("cls");
while (readGrades >> studentId >> examGrade1 >> examGrade2 >> examGrade3)
{
if (searchId == studentId)
{
cout << left
<< "Student ID\t" << "Exam 1\t" << "Exam 2\t" << "Exam 3\t" << endl;
cout << "======================================" << endl;
cout << left << setw(4) << studentId << "\t\t"
<< fixed << setprecision(2)
<< left << setw(5) << examGrade1 << "\t"
<< left << setw(5) << examGrade2 << "\t"
<< left << setw(5) << examGrade3 << endl;
system("pause");
break;
}
else
cout << "Entered ID not found";
}
}
else
{
cout << "Error opening file!\n";
}
cout << endl; }
现在的问题是else语句。我应该提示用户某个ID不存在。但是我不知道如何使else语句仅在while语句中运行一次。每次我搜索不存在的ID时,无论读取输入多少次,它都会说“找不到输入的ID”。
所以结果看起来像这样。 No ID Found
同时,如果我输入的ID确实存在但在文件中排在第三位,它将看起来像这样。 ID Found
我从逻辑上知道发生了什么,但是它多次运行while循环。但是我不知道该如何处理。任何将我引向正确方向的帮助都会有帮助。我是编码/ C ++的新手,对搜索文件中的内容不太熟悉。谢谢!
答案 0 :(得分:1)
else
块放置在错误的位置。您需要更新逻辑,以便仅当遍历整个文件后未找到学生证时才打印该消息。这意味着它已经超出了while
循环。
if (readGrades)
{
bool found = false;
while (readGrades >> studentId >> examGrade1 >> examGrade2 >> examGrade3)
{
if (searchId == studentId)
{
cout << left
<< "Student ID\t" << "Exam 1\t" << "Exam 2\t" << "Exam 3\t" << endl;
cout << "======================================" << endl;
cout << left << setw(4) << studentId << "\t\t"
<< fixed << setprecision(2)
<< left << setw(5) << examGrade1 << "\t"
<< left << setw(5) << examGrade2 << "\t"
<< left << setw(5) << examGrade3 << endl;
found = true;
break;
}
}
if ( !found )
{
cout << "Entered ID not found";
}
}