C++:从文件中读取数据以填充链表

标签 c++ linked-list

我正在尝试获取一个包含 8 行的 .dat 文件,第一行是记录数,其余 7 行包含将填充链表的记录数据。

我遇到的问题是我的代码只填充第一条记录,但使用 cout 我知道它遍历整个文件。这是我正在使用的代码片段:

fstream listBuilder;
listBuilder.open("HW06.dat");

if ( listBuilder.is_open() ) {
    TeleType *current;
    current = listHead;

    listBuilder >> numberOfRecords;

    while ( listBuilder ) {
        string firstName;
        string lastName;
        string phone;
        string name;

        listBuilder >> firstName >> lastName >> phone;

        name = firstName + " " + lastName;
        current->name = name;
        current->number = phone;

        current = current->nextaddr;
        current = new TeleType;
    }

    listBuilder.close();
} // end if
else {
    cout << "***** Error: File failed to open. *****" << endl;
} // end else

最佳答案

你应该先创建下一个节点然后指向它,而不是相反!!

current->nextaddr = new TeleType; 
current = current->nextaddr;

关于C++:从文件中读取数据以填充链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43551622/

相关文章:

c - 将 C 字符串插入链表时出现问题

c - 释放链表时堆栈溢出 : Segmentation fault after 100k nodes successfully freed

c++ - CppUnit 和 CMake : . cpp 文件被编译两次

可变参数模板参数的 C++ 约束

c++ - 具有数字部分的字符序列

c# - 拦截与获取Windows版本相关的API调用

c - 链表-获取段错误

c - 将NULL分配给C中链表中的头节点

java - 将值添加到列表并转换为 BigInteger - Java

c++ - C++中的fread和strncpy中的缓冲区溢出