C 链接列表 - 带有前哨的文件中读取数据
C++ Linked List - Reading data from a file with a sentinel
所以我对此做了很多研究,无法使我的输出正常工作。我需要从文件中读取数据,并将其存储到链接列表中。使用的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 != "$$$$$")
您无法将流与" $$$$$"进行比较。您只能读取流中的字符串,并将其比较" $$$$$"。
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量