将从格式化文本文件读取的文本数据存储到链表

Store text data read from a formatted text file to a linked list

本文关键字:文本 存储 数据 链表 读取 格式化 文件      更新时间:2023-10-16

我正在为学生课程注册系统做一个项目。我在从文本文件中读取数据并将其存储在单向链表中时遇到问题,每次添加新学生时都必须更新该列表。数据以格式化方式存储。问题是我的结构具有char类型的变量,因此它给我分配错误。

结构定义为:

struct Student {
char stdID[10];
char stdName[30];
char stdSemester[5];
Student  *next; } *Head, *Tail;

保存结构的代码为:

// For Saving: 
SFile << std->stdID << 't' << std->stdName << 't' << std->stdSemester << 'n';

读取文本文件和显示结构的代码为:

// Display:
system("cls");
cout << "nnn";
cout << "tttt           LIST OF COURSES" << endl;
cout << "ttt   ====================================================n" << endl;
cout << "t" << "ID" << "t" << setw(15) << "Course Name" << "nn";
// Initialize:
char ID[10];
char Name[30];
char Sem[5]; 
ifstream SFile("StudentRecord.txt");
Student *Temp = NULL;
while(!SFile.eof()) {
// Get:
SFile.getline(ID, 10, 't');
SFile.getline(Name, 30, 't');
SFile.getline(Sem, 5, 't');
Student *Std = new Student;   //<======== OUCH! Assignment error here
//node*c=new node;
// Assign:
Std->stdID = *ID;
if (Head == NULL) {
Head = Std;
} 
else {
Temp = Head;
{
while ( Temp->next !=NULL ) {
Temp=Temp->next;
}
Temp->next = Std;
}
}
}
SFile.close();
system("pause"); }

PS:我在分配评论时遇到问题;

我是否必须更改数据类型并使整个项目string?我更喜欢char,因为我能够格式化输出,并且string我确定它会逐行读取,所以我将无法存储单行的值。

使用字符串?

如果 ID 是std:string,您可以执行以下操作:

Std->stdID = ID;

您可以使用std::getline()

getline(SFile, ID, 't');

您不必担心最大长度,但您仍然可以决定检查字符串的 lngth 并在必要时缩短它。

还是不使用字符串?

但是,如果您更喜欢(或必须(使用char[],那么您需要使用strncpy()来执行作业:

strncpy( Std->stdID, ID, 10 );  // Std->stdID = *ID;

尊敬的是,在 21 世纪,我会选择 std::string,而不是坚持可以追溯到 70 年代的旧char[]......

文件循环

这是不相关的,但你永远不应该循环eof

while (SFile.getline(ID, 10, 't') 
&& SFile.getline(Name, 30, 't')  && SFile.getline(Sem, 5, 'n') {
...
}

为什么? 在此处查看更多解释

顺便说一下,根据你的写作功能,你的最后getline()当然应该寻找'n'作为分隔符。