c++ - 打印逐行存储的文本文件
问题描述
我试图编写一个搜索 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
解决方案
因此,您的代码中存在一个逻辑缺陷,使您更难做您想做的事。图书数据存储在三个单独的行中,但您的代码一次读取一行。从逻辑上讲,您应该一次阅读三行。通过这样做,您将同时获得一本书的所有信息。
像这样
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 条件的一部分。我们不想仅仅因为一本书后面没有空行而不考虑它。例如,这可能发生在文件末尾。
推荐阅读
- javascript - 如何在单独的js文件中实现类构造函数中的路由器(express)
- r - 如何计算多个数字列的每行平均值
- asp.net-core - Microsoft.Entity.FrameworkCore 中发生版本冲突
- x11 - Ghostscript 在错误的地方寻找 dyld 库
- react-native - Twilio 可编程聊天消息用户友好名称
- python - 如何将 keras 模型导入 Lucid
- docker - PHP 无法解析主机名
- javascript - 从文本区域中查找所有超链接并添加 rel nofollow
- javascript - 为什么Javascript对象值在对象中的键而不是变量中发生变化?
- java - 线程内控制台中没有空指针异常消息