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

时间:2018-02-26 15:48:22

标签: c++ file structure getline display

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

2 个答案:

答案 0 :(得分:2)

您需要的包含库以及Book结构定义。一旦学习了更高级的C ++主题,您就可以学习如何为输入和输出流重载友元函数,以使{/ 1}}对象的I / O操作自包含。

Book

如果你有输入文件的句柄,你可以像这样解析它。一次读取每一行。 Do not read until input.eof()因为它错了!将每行存储到临时#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 }; 对象中以进行进一步解析。使用重载的std::istringstreamstd::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

答案 1 :(得分:-3)

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

struct Book {
    string title;
    string author;
    string price;
};
void read_Books(std::ifstream&, Book&);

int main()
{
    ifstream p("books.txt", ios::in);
    Book a;
    read_Books(p, a);
    return 0;
}
void read_Books(std::ifstream& p, Book& ptstr) {
    while(p.is_open() && !p.eof()){
        getline(p, ptstr.title, '|');
        getline(p, ptstr.author, '|');
        getline(p, ptstr.price, '|');
        cout<<ptstr.title << ptstr.author << ptstr.price << std::endl;
        //The whole line is printed, it ought to be the title only
    }
}