首页 > 解决方案 > 打印逐行存储的文本文件

问题描述

我试图编写一个搜索 ID 并打印书名和作者姓名的函数。我已经能够匹配 ID,但无法正确打印书籍和作者姓名。文本文件存储如下:

ID
book name 
author name

以下是我的搜索功能的代码:

void searching() {
    string search, id, name;
    ifstream myfile("books.txt");
    bool found = false;
    string line;
    cout << "\nEnter ID to search : ";
    cin >> search;
    int srchlen = search.length();
    if(myfile.is_open()) {
        while(getline(myfile, line)) {
            id = line.substr(0, srchlen);
            if(id == search) {
                found = true;
                break;
            } else {
                found = false;
            }
        }

        if(found == true) {
            name = line;
            cout << "ID\tNAME\tAUTHOR\n";
            cout << name;

        } else {
            cout << "ID doesnt exist";
        }
    }
}

这是文本文件的样子(每本书之间有一个空行):

98
crime and punishment
Dostoevsky

70
The Da Vinci Code
Dan Brown

标签: c++

解决方案


因此,您的代码中存在一个逻辑缺陷,使您更难做您想做的事。图书数据存储在三个单独的行中,但您的代码一次读取一行。从逻辑上讲,您应该一次阅读三行。通过这样做,您将同时获得一本书的所有信息。

像这样

string id, title, author;
while (getline(myfile, id) && getline(myfile, title) && getline(myfile, author)) {
    string blank;
    getline(myfile, blank); // skip the blank line between books
    id = id.substr(0, srchlen);
    if (id == search) {
        found = true;
        break;
    } else {
        found = false;
    }
}
if (found == true) {
    cout << "ID\tNAME\tAUTHOR\n";
    cout << id << ' ' << title << ' ' << author << '\n';;
} else {
    cout << "ID doesnt exist";
}

请注意,读取空白行不是 while 条件的一部分。我们不想仅仅因为一本书后面没有空行而不考虑它。例如,这可能发生在文件末尾。


推荐阅读