如何从文本文件中读取某些元素?

时间:2017-12-06 03:52:20

标签: c++ getline

我有一个包含多组图书信息(标题,作者等)的文本文件。我需要能够使用循环从文件中读取并将每条信息分配给相应的字符串。我让它在我浏览整个文件的地方工作,它只是在浏览文件时搞砸了。

Book readOne(ifstream &fin) {
string titleOne;
getline(fin, titleOne, ',');
string firstOne;
getline(fin, firstOne, ',');
string lastOne;
getline(fin, lastOne, ',');
string formatOne;
getline(fin, formatOne, ',');
string pubDateOne;
getline(fin, pubDateOne, ',');
string priceOne;
getline(fin, priceOne);

这是文本文件:

Gone With the Wind, Margaret Mitchell, Hardcover, 1936, 17.49
The Adventures of Sherlock Holmes, Arthur Doyle, Paperback, 1892, 6.85
The Illustrated A Brief History of Time, Stephen Hawking, Hardcover, 1996, 9.59
Frankenstein, Mary Shelley, Paperback, 1818, 7.99 
Command Authority, Tom Clancy, Paperback, 2013, 15.99
Origin, Dan Brown, Ebook, 2017, 14.99
The Lost Order, Steve Berry, Audiobook, 2017, 5.95
The Hunt for Red October, Tom Clacy, Audiobook, 1984, 7.00
Patriot Games, Tom Clancy, Audiobook, 1987, 22.50
The 14th Colony, Steve Berry, Paperback, 2016, 9.99
The Bishop's Pawn, Steve Berry, Ebook, 2018, 14.99
Pride and Prejudice, Jane Austen, Ebook, 1813, 8.99
Sense and Sensibility, Jane Austen, Hardcover, 1811, 19.99
Wuthering Heights, Emily Bronte, Paperback, 1847, 6.99
Jane Eyre, Charlotte Bronte, Hardcover, 1847, 10.95 
Anna Karenina, Leo Tolstoy, Paperback, 1877, 5.99
Sahara, Clive Cussler, Ebook, 1992, 5.99
The Notebook, Nicholas Sparks, Hardcover, 1996, 12.59
A Walk to Remember, Nicholas Sparks, Ebook, 1999, 7.99
See Me, Nicholas Sparks, Ebook, 2015, 7.99
The Last Song, Nicholas Sparks, Paperback, 2009, 5.99
The Wedding, Nicholas Sparks, Ebook, 2003, 7.99

我的想法是它会读到逗号,将该信息分配给字符串,然后继续。相反,它输出就好像它没有看到某些逗号。

Gone With the Wind by  Margaret Mitchell  Hardcover on  1936. Published on  17.49
The Adventures of Sherlock Holmes. It costs $0
The Illustrated A Brief History of Time by  Stephen Hawking  Hardcover on  1996. Published on  9.59
Frankenstein. It costs $0
Command Authority by  Tom Clancy  Paperback on  2013. Published on  15.99
Origin. It costs $0
The Lost Order by  Steve Berry  Audiobook on  2017. Published on  5.95
The Hunt for Red October. It costs $0
Patriot Games by  Tom Clancy  Audiobook on  1987. Published on  22.50
The 14th Colony. It costs $0
The Bishop's Pawn by  Steve Berry  Ebook on  2018. Published on  14.99
Pride and Prejudice. It costs $0
Sense and Sensibility by  Jane Austen  Hardcover on  1811. Published on  19.99
Wuthering Heights. It costs $0
Jane Eyre by  Charlotte Bronte  Hardcover on  1847. Published on  10.95
Anna Karenina. It costs $0
Sahara by  Clive Cussler  Ebook on  1992. Published on  5.99
The Notebook. It costs $0
A Walk to Remember by  Nicholas Sparks  Ebook on  1999. Published on  7.99
See Me. It costs $0
The Last Song by  Nicholas Sparks  Paperback on  2009. Published on  5.99
The Wedding. It costs $0

1 个答案:

答案 0 :(得分:0)

这只是一个csv(逗号分隔值)文件。并且有足够的代码示例来读取它。请参阅this sample