将从格式化文本文件读取的文本数据存储到链表
Store text data read from a formatted text file to a linked list
我正在为学生课程注册系统做一个项目。我在从文本文件中读取数据并将其存储在单向链表中时遇到问题,每次添加新学生时都必须更新该列表。数据以格式化方式存储。问题是我的结构具有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'
作为分隔符。
相关文章:
- 打印逐行存储的文本文件
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 是否保证相同内容字符串文本的存储相同?
- 从文本文件读取,然后将项目存储到列表中
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 如何将函数的输出数据存储在文本文件中
- 如何在不知道大小的情况下读取文本文件并存储到数组中
- 将文本文件中的文本存储到六个不同的矢量中(C++)
- 为什么使用 C++ 中的类对象写入文件中的数据以非文本格式存储?
- C++读取文本文件并存储数据
- 如何有效地读取和存储 1GB 文本文件中的数据
- 是否可以将来自 Win32 EDIT 控件的文本输入存储在C++ std::string 中?
- std::bad_alloc 将文本文件中的单个字符存储到矢量C++中时
- C ++将文本存储在数组的不同索引中,并带有一两个
- 将大文本文件存储到矢量中并循环访问它
- 从文本文件中读取整数并将它们存储到数组中
- 无法将文本存储在SFML 2.4中
- 将包含空格的文件中的文本存储为字符串