用C++从txt文件中读取书籍信息?

А.Петров

我想阅读书籍 - txt 文件中的书名、作者和价格。The 3 properties of the book are separated by '|' - Title|Author|Book.但是,我不知道如何做到这一点。我有结构 Book,有 3 个元素。我想,对于每行读取书名,作者和价格,将它们分别保存到结构的3个变量中并在控制台上打印它们。我试图只用标题来做这个,但它打印了整行。请问如何分别打印每本书的作者名称和价格?

贾斯汀兰德尔

您将需要的包含库以及您的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
};

如果您有输入文件的句柄,则可以像这样解析它。一次阅读每一行。在 input.eof() 之前不要阅读,因为它是错误的!将每一行存储到一个临时std::istringstream对象中以供进一步解析。使用重载的std::getline(stream, token, delimiter)with|来解析行中的数据,直接保存到你的临时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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章