C 链接列表 - 带有前哨的文件中读取数据

C++ Linked List - Reading data from a file with a sentinel

本文关键字:文件 读取 数据 前哨 链接 列表      更新时间:2023-10-16

所以我对此做了很多研究,无法使我的输出正常工作。我需要从文件中读取数据,并将其存储到链接列表中。使用的while循环一旦击中$$$$$哨兵就应该停止。然后,我要显示数据(通过ID编号[用户输入]搜索)我还不是那么远,但我只想正确显示数据并立即将其读入。

我的问题是显示数据并没有停止在$$$$上(即使我做" infile.peek()!= eof并忽略$$$$$$)额外的垃圾记录。

我知道这与我的时循环以及我如何创建新节点有关,但我无法其他任何方式工作。

任何帮助将不胜感激。

学生.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;

};

nistion6imp.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;
}
}

也许您应该尝试逐行读取行,就像这样。

const string END_OF_FILE_DELIM = "$$$$$";
ifstream inFile("students.txt");
string line;
while( getline(inFile,line) ){
   cout << "line = " << line << endl;
   if(line == END_OF_FILE_DELIM){
      break;
   }
   else{
       //create new Node with value = line;
   }
}

这无法工作:

if (inFile != "$$$$$")

您无法将流与" $$$$$"进行比较。您只能读取流中的字符串,并将其比较" $$$$$"。