0

Below is part of an assignment I am working on. I am stuck. A little background:

  1. BookClass is a class built for this assignment, I know it works as it should from a previous assignment.

  2. Opening the file and reading the first time works like it should. Immediately after the loop starts again it skips a complete line and the book authors name becomes the book title and so on.....leaving booksInStock with nothing.

My question is, what is causing "getline(file, bookTitle)" to be skipped?

I also attached an image that might help a bit in explaining it in more detail.Screenshot of example

void getBookInfo(BookClass &book)  
{
    string  bookTitle,
            authorName,
            bookPublisher,
            bookISBN;
    double  bookPrice;
    int     bookYear,
            booksInStock,
            count = 0;
    ifstream file;

    file.open("books.txt"); 

    while (!file.eof()) 
    {
        getline(file, bookTitle);
        getline(file, authorName);
        getline(file, bookPublisher);
        getline(file, bookISBN);
        file >> bookPrice;
        file >> bookYear;
        file >> booksInStock;

        book.storeBook(bookTitle, authorName, bookPublisher, bookISBN, 
                       bookPrice, bookYear, booksInStock);  //member function of 
                                                              built class to store info
        books[count] = book;  
        count++;  
    }
    file.close();   
}

CORRECT:

    getline(file, bookTitle);
    getline(file, authorName);
    getline(file, bookPublisher);
    getline(file, bookISBN);
    file >> bookPrice;
    file >> bookYear;
    file >> booksInStock;
    file.ignore();
Nalaedge
  • 1
  • 4
  • What does the input file (`books.txt`) look like. – Annie the Eagle Nov 02 '18 at 16:21
  • 3
    Two questions you should read: [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction), and [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). The former of these is a duplicate to your question; the latter is something you definitely need to be aware of. – WhozCraig Nov 02 '18 at 16:22
  • TL;DR of the dupe: add `file.ignore(std::numeric_limits::max(), '\n') ` to the end of the loop. – NathanOliver Nov 02 '18 at 16:22
  • The file is 1 line per variable....no spaces between. I have checked the file to make sure it does not have any errant spaces. – Nalaedge Nov 02 '18 at 17:01
  • ugh....I am an idiot newbie.......file.ignore()......fixed it like it should! – Nalaedge Nov 02 '18 at 17:04
  • Thanks for your direction...I have lurked for sometime...but never questioned. – Nalaedge Nov 02 '18 at 17:05
  • I added what I changed..... – Nalaedge Nov 02 '18 at 18:09

0 Answers0