因此,我对此进行了大量研究,但无法使我的输出正常工作。我需要从文件中读取数据并将其存储到链接列表中。使用的 while 循环应在遇到 $$$$$ 标记后停止。然后我要显示数据(通过 ID 号 [用户输入] 搜索)我还没有那么远,但我只想正确显示数据并立即读取它。
我的问题是当它显示数据没有停止在 $$$$ 时(即使我执行 "inFile.peek() != EOF 并省略 $$$$)我仍然会收到额外的垃圾记录。
我知道这与我的 while 循环以及我如何创建一个新节点有关,但我无法让它以任何其他方式工作。
任何帮助,将不胜感激。
学生.txt
Nick J Cooley
324123
60
70
80
90
Jay M Hill
412254
70
80
90
100
$$$$$
分配6.h文件
#pragma once
#include <iostream>
#include <string>
using namespace std;
class assign6
{
public:
assign6(); // constructor
void displayStudents();
private:
struct Node
{ string firstName;
string midIni;
string lastName;
int idNum;
int sco1; //Test score 1
int sco2; //Test score 2
int sco3; //Test score 3
int sco4; //Test score 4
Node *next;
};
Node *head;
Node *headPtr;
};
assign6Imp.cpp // 实现文件
#include "assign6.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
assign6::assign6() //constructor
{
ifstream inFile;
inFile.open("students.txt");
head = NULL;
head = new Node;
headPtr = head;
while (inFile.peek() != EOF) //reading in from file and storing in linked list
{
inFile >> head->firstName >> head->midIni >> head->lastName;
inFile >> head->idNum;
inFile >> head->sco1;
inFile >> head->sco2;
inFile >> head->sco3;
inFile >> head->sco4;
if (inFile != "$$$$$")
{
head->next = NULL;
head->next = new Node;
head = head->next;
}
}
head->next = NULL;
inFile.close();
}
void assign6::displayStudents()
{
int average = 0;
for (Node *cur = headPtr; cur != NULL; cur = cur->next)
{
cout << cur->firstName << " " << cur->midIni << " " << cur->lastName << endl;
cout << cur->idNum << endl;
average = (cur->sco1 + cur->sco2 + cur->sco3 + cur->sco4)/4;
cout << cur->sco1 << " " << cur->sco2 << " " << cur->sco3 << " " << cur->sco4 << " " << "average: " << average << endl;
}
}