【问题标题】:Store text data read from a formatted text file to a linked list将从格式化文本文件读取的文本数据存储到链表
【发布时间】: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,我确定它是逐行读取的,所以我无法存储单行的值。

【问题讨论】:

  • 我更喜欢 char 因为我能够格式化输出, char 应该很少比 std::string 更受欢迎。如果你使用std::string,你的程序会更简单。
  • @drescherjm Std-&gt;stdID = *ID; 是一个“分配错误”。
  • @Vikesyy “在字符串中我确定它是逐行读取的,所以我无法存储单行的值。”您可以像现在使用 char 数组一样使用 std::strings 和 getline() 和分隔符。
  • @Vikesyy 您不必必须,但这会让您的生活更轻松。

标签: c++ data-structures singly-linked-list formatted-input


【解决方案1】:

要使用字符串?

如果 ID 是 std:string,您可以这样做:

Std->stdID = ID;

你可以使用std::getline():

getline(SFile, ID, '\t');

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

还是不使用字符串?

但如果您更喜欢(或必须)改用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') {
   ...
}

为什么?看here for more explanations

顺便说一句,根据您的写作功能,您最后的getline() 肯定应该寻找'\n' 作为分隔符。

【讨论】:

  • Std-&gt;stdID = ID
  • 我实际上不理解“eof”,你能解释一下它是如何不相关的吗?抱歉,我是编程新手。
  • @Vikesyy by "its unrealeated" Christophe 想说他提到的关于您使用eof 的内容与您所询问的内容无关。你应该看看stackoverflow.com/questions/5605125/…
  • @Christophe 谢谢你意味着很多!
  • @Christophe 如果我不想使用流大小,只有限制器,我能从文本文件中获取所有输入吗?
猜你喜欢
  • 2017-08-06
  • 2021-03-25
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
相关资源
最近更新 更多