C++ 要求用户输入studentID。然后,您将打开文本文件并搜索此ID。(C+;+;)

C++ 要求用户输入studentID。然后,您将打开文本文件并搜索此ID。(C+;+;),c++,C++,我需要在文本文件中输入一个ID号,并输出文本文件同一行上的相关等级 这是我的代码,它打印正确的平均值,但它打印下一个ID数字的测试分数 int searchID; int studentID; bool found = false; double exam_1; double exam_2; double exam_3; double average = 0; cout << "Enter student ID to search in file " << f

我需要在文本文件中输入一个ID号,并输出文本文件同一行上的相关等级

这是我的代码,它打印正确的平均值,但它打印下一个ID数字的测试分数

int searchID;
int studentID;
bool found = false;

double exam_1;
double exam_2;
double exam_3;
double average = 0;

cout << "Enter student ID to search in file " <<
    fileName << " : ";
//read searchID value
cin >> searchID;

//read data from file until the search id is found
while (fin >> studentID >> exam_1 >> exam_2
    >> exam_3 && !found)
{
    if (searchID == studentID)
    {
        average = (exam_1 + exam_2 + exam_3) / 3.0;
        found = true;
    }
}
//close the file stream,fin
fin.close();
//check if search id is found
if (found)
{
    cout << left << setw(10) << "Exam 1" << setw(10) << exam_1 << endl;
    cout << left << setw(10) << "Exam 2" << setw(10) << exam_2 << endl;
    cout << left << setw(10) << "Exam 3" << setw(10) << exam_3 << endl;
    cout << fixed << setprecision(2)
        << "Average : " << average << endl;
}
else
    cout << searchID << " student id is not found." << endl;

system("pause");
int-searchID;
国际学生;
bool-found=false;
复试1;
复试2;
复试3;
双平均=0;
课程>学生ID>>考试1>>考试2
>>考试3&!发现)
{
if(searchID==studentID)
{
平均值=(考试1+考试2+考试3)/3.0;
发现=真;
}
}
//关闭文件流,fin
fin.close();
//检查是否找到搜索id
如果(找到)
{

cout您的循环条件错误。假设一次迭代发现了
ID
found
设置为true,然后对下一次迭代的条件进行评估:

while (fin >> studentID >> exam_1 >> exam_2 >> exam_3 && !found)
无论
found
的值是多少,您都会读取文件中的下一个条目。将其更改为

while (!found && fin >> studentID >> exam_1 >> exam_2 >> exam_3)

和&
短路,即当
!found
false
时,不评估其余条件。

无关:什么是
文件名
?什么是
fin
?请尝试创建一个显示,最好是一个显示所有变量以及它们是如何初始化的,如果可能,只供我们复制粘贴能够复制您遇到的问题。但有一点关于您的问题的提示:了解并思考在循环条件下执行操作的顺序可能会受到它的影响。
while(fin>>studentID>>test\u 1>>test\u 2>>test\u 3&!found)
--大声读那一行。它告诉你什么?读一行新行,如果你以前发现了什么,不要循环。这就是你想要的,读一行新行,破坏以前的结果吗?你不应该先检查你是否发现了什么,如果没有找到,然后再读新行吗?这都归结为简单的逻辑——这是错误的爱丽:没有什么可争的。@PaulMcKenzie你说得对,对不起,我没有注意到,是的,我在争,这完全没问题