您需要的包含库,以及您的Book 结构定义。一旦你开始学习更高级的 C++ 主题,你就可以学习如何为输入和输出流重载友元函数,以使你的 I/O 操作为 Book 对象自包含。
#include <iostream> ///< std::cout
#include <fstream> ///< std::ifstream
#include <sstream> ///< std::istringstream, std::string
#include <vector> ///< std::vector
struct Book
{
std::string title; ///< title of the book
std::string author; ///< author of the book
std::string price; ///< price of the book (TODO use float instead?)
// TODO consider friend std::istream& operator>> for parsing input data
// TODO consider friend std::ostream & operator<< for printing object
};
如果你有输入文件的句柄,你可以像这样解析它。一次阅读每一行。 Do not read until input.eof() 因为错了!将每一行存储到一个临时的std::istringstream 对象中以供进一步解析。使用重载的std::getline(stream, token, delimiter) 和| 来解析行中的数据,并将它们直接保存到您的临时Book 对象中。最后,如果您希望以后能够处理它们,请将对象存储到您的向量中,并可选择将它们打印到控制台。
void readBooks(std::ifstream& input, std::vector<Book>& books)
{
std::string line;
while (std::getline(input, line)) ///< while we have a line to parse
{
std::istringstream iss(line); ///< line to parse as sstream
Book book; ///< temporary book object
std::getline(iss, book.title, '|');
std::getline(iss, book.author, '|');
std::getline(iss, book.price, '|');
books.push_back(book); ///< add book object into vector
std::cout << "Title: " << book.title << std::endl;
std::cout << "Author: " << book.author << std::endl;
std::cout << "Price: " << book.price << std::endl << std::endl;
}
}
int main()
{
std::vector<Book> books; ///< store each Book object
std::ifstream input("books.txt");
if (input.is_open())
{
readBooks(input, books); ///< read your books
}
return 0;
}
使用以下输入文件内容测试
Tales from Shakespeare (1807)|Shakespeare|6.74
The Jungle Book (1894)|Rudyard Kipling|9.99
Through the Looking-Glass (1871)|Lewis Carroll|12.97
得到以下结果
Title: Tales from Shakespeare (1807)
Author: Shakespeare
Price: 6.74
Title: The Jungle Book (1894)
Author: Rudyard Kipling
Price: 9.99
Title: Through the Looking-Glass (1871)
Author: Lewis Carroll
Price: 12.97