【问题标题】:checking a line ahead while reading a file before created a new node在创建新节点之前读取文件时检查前面的一行
【发布时间】:2020-05-02 08:00:32
【问题描述】:

file being read

outPut of said file

我正在尝试从文件中读取数据并将其数据存储在我的链表中。我遇到的问题是,当我读取包含第二个地址的人的信息时,我的函数仅使用包含两个地址的数据更新我的链表。注意:打印我的链接列表时,它是相反的顺序,因为在每个节点之前。注意底部的 5 个打印语句如何包含 1 个地址,这些是我从文件中检索的前 5 行。一旦函数到达包含两个地址的第 6 行,它就无法使用仅包含 1 个地址的数据更新我的列表。但是,它会继续更新我的列表中包含 2 个地址的两个数据。

void AddressBook::readFile(string fileName) {

    ifstream f(fileName);

    string firstName = "", lastName, phoneNumber, buildingNumber, street, city, state, zipCode, buildingNumber_2, street_2, city_2, state_2, zipCode_2, entry;
    bool twoAddr = false;

    if (!f.is_open()) { die("file not open"); }

    while (f >> entry) {
        if (isdigit(entry[0])) {
            buildingNumber_2 = entry;
            f >> street_2 >> city_2 >> state_2 >> zipCode_2;
            addEntry(Person(firstName, lastName, phoneNumber, Address(buildingNumber, street, city, state, zipCode), Address(buildingNumber_2, street_2, city_2, state_2, zipCode_2)));
                twoAddr = true;
        }
        else {
            if (firstName != "" && !twoAddr) {
                addEntry(Person(firstName, lastName, phoneNumber, Address(buildingNumber, street, city, state, zipCode)));
                twoAddr = false;
            }
            firstName = entry;
            f >> lastName >> phoneNumber >> buildingNumber >> street >> city >> state >> zipCode;
        }
    }
}



【问题讨论】:

    标签: c++ file storage


    【解决方案1】:

    尝试实现这个算法:

    for (;;) {
      line = file.readline();
      if (is_person_line(line))
        addEntry(create_person(line));
      else if (is_address_only(line))
        entries[-1].add_address(create_address(line));
    }
    
    

    它还应该使您的代码更清晰。

    【讨论】:

    • 但是由于我要添加到链表的前面,我可以添加一个地址
    • 这就是所谓的“伪代码”,一种解决方案的想法。 readlinecreate_person 之类的函数应该由您实现,我知道您知道如何实现它们,因为我在您的代码中看到了它们。
    • 抱歉,我认为可能有一种方法可以将整行传递给班级。我现在把它放在一起。之后我会再次发表评论。
    • 它可以工作,但由于某种原因,我的 setter 函数没有使用当前地址更新,或者我的打印函数正在显示之前的副本
    • Getters 使用副本,因此如果您使用引用,它可以解决该问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多