【发布时间】:2018-10-22 17:58:30
【问题描述】:
我正在开发一个学生课程注册系统项目。我在从文本文件中读取数据并将其存储在单链表中时遇到问题,每次添加新学生时都必须更新单链表。数据以格式化的方式存储。问题是我的结构有类型 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 << "\n\n\n";
cout << "\t\t\t\t LIST OF COURSES" << endl;
cout << "\t\t\t ====================================================\n" << endl;
cout << "\t" << "ID" << "\t" << setw(15) << "Course Name" << "\n\n";
// 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"); }
P.S:我在分配评论时遇到问题;
我是否必须更改数据类型并在string 中创建整个项目?我更喜欢char,因为我能够格式化输出,而在string,我确定它是逐行读取的,所以我无法存储单行的值。
【问题讨论】:
-
while(!SFile.eof()) {stackoverflow.com/questions/5605125/… -
我更喜欢 char 因为我能够格式化输出, char 应该很少比
std::string更受欢迎。如果你使用std::string,你的程序会更简单。 -
@drescherjm
Std->stdID = *ID;是一个“分配错误”。 -
@Vikesyy “在字符串中我确定它是逐行读取的,所以我无法存储单行的值。”您可以像现在使用
char数组一样使用std::strings 和getline()和分隔符。 -
@Vikesyy 您不必必须,但这会让您的生活更轻松。
标签: c++ data-structures singly-linked-list formatted-input