Note that there are some explanatory texts on larger screens.

plurals
  1. POReading a file line by line with strings and integers
    text
    copied!<p>I'm trying to read the information from the following file:</p> <pre><code>The Firm Dell 512 Fundamentals of Computer Graphics A K Peters, Ltd. 662 The C++ Programming Language Addison-Wesley Professional 911 Northwest Airlines Plymouth Toy &amp; Book 96 Lonely Planet: Europe on a Shoestring Lonely Planet Publications 1324 … </code></pre> <p>The file lists books with the first line being the Title, second line is Publisher, and third line is Number of pages.It repeats for five books. I'm trying to read the information and store them into the vector in the Library class.</p> <pre><code>class book { public: book(); book(string t, string p, int num); string getTitle(); string getPublisher(); int getPageNum(); void setTitle(string t); void setPublisher(string p); void setPageNum(int num); string title; string publisher; int num_of_pages; }; class library { public: vector&lt;book&gt; collection; bool contains(string title); void addBook(book b); void readFile(string fileName); } </code></pre> <p>Here is the readFile function:</p> <pre><code> void library::readFile(string fileName) { ifstream infile; infile.open(fileName.c_str()); if (infile.fail()) { cout&lt;&lt;"Error opening file."&lt;&lt;endl&lt;&lt;endl; exit(1); } book addition; string line; while (!infile.eof()) { getline(infile, addition.title); getline(infile, addition.publisher); getline(infile, line); addition.num_of_pages=atoi(line.c_str()); collection.push_back(addition); } collection.push_back(addition); } </code></pre> <p>One final issue: The output is not working properly. Everything in the file is listed under the title. </p> <pre><code>ostream &amp;operator &lt;&lt;(ostream&amp; out, const book&amp; b1) { out&lt;&lt;"TITLE: "&lt;&lt;b1.title&lt;&lt;endl; out&lt;&lt;"PUBLISHER: "&lt;&lt;b1.publisher&lt;&lt;endl; out&lt;&lt;"NUMBER OF PAGES: "&lt;&lt;b1.num_of_pages&lt;&lt;endl; return out; } </code></pre> <p>Main code:</p> <pre><code>int i; for (i=0; i&lt;book_library.collection.size(); i++) { cout&lt;&lt;book_library.collection[i]&lt;&lt;endl; } </code></pre> <p>Output:</p> <pre><code>TITLE: The Firm Dell 512 Fundamentals of Computer Graphics A K Peters, Ltd. 662 The C++ Programming Language Addison-Wesley Professional 911 Northwest Airlines Plymouth Toy &amp; Book 96 Lonely Planet: Europe on a Shoestring Lonely Planet Publications 1324 \311 PUBLISHER: NUMBER OF PAGES: 0 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload