C ++:从文件读入数据以填充链接列表

时间:2017-04-21 20:36:56

标签: 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

1 个答案:

答案 0 :(得分:1)

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

current->nextaddr = new TeleType; 
current = current->nextaddr;
相关问题