0

The gist of my problem is that I am reading a file with fields separated by #'s except for the end of the line. When I look at the print statements for the fields that I am reading into a book struct (that uses a for loop to go through the entire data file/list of books (theoretically)), they all have the same value. For example, there are 200 of the exact same id followed by 200 of the exact same title instead of reading farther down on the data file.

The exact code is:

void loadTable(book table[], int size){
    for (int i = 0; i < size; i++){
        book newBook;
        ifstream ifs("inventory.txt");
        string bit;
        getline(ifs, bit, '#');
        newBook.bookId = atoi(bit.c_str());
        cout << "BookID: " << newBook.bookId;
        getline(ifs, bit, '#');
        newBook.title = bit;
        cout << "Title: " << newBook.title;
        getline(ifs, bit, '#');
        newBook.author = bit;
        getline(ifs, bit, '#');
        newBook.cost = atof(bit.c_str());
        getline(ifs, bit, '#');
        newBook.price = atof(bit.c_str());
        getline(ifs, bit);
        newBook.quantity = atoi(bit.c_str());
        loadBook(table, newBook, size);
    }

}

And the exact result:

tiesBookID: 116807Title: A Tale of Two CitiesBookID: 116807Title: A Tale of Two
CitiesBookID: 116807Title: A Tale of Two CitiesBookID: 116807Title: A Tale of Tw
o CitiesBookID: 116807Title: A Tale of Two CitiesBookID: 116807Title: A Tale of
Two CitiesBookID: 116807Title: A Tale of Two CitiesBookID: 116807Title: A Tale o
f Two CitiesBookID: 116807Title: A Tale of Two CitiesBookID: 116807Title: A Tale
 of Two CitiesBookID: 116807Title: A Tale of Two CitiesBookID: 116807Title: A Ta
...
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user963070
  • 629
  • 2
  • 19
  • 24

1 Answers1

5

Why do you always open you file inside the for loop? You should first open the file, then loop through the file and put the contents you read from file into the struct. In this case, you are always reading the first several lines which contains information about the first book since you open the file again and again, meanwhile, you did not close your file, which is not good.

taocp
  • 23,276
  • 10
  • 49
  • 62