0

I made a simple program that calculates price for items sold. And saves the information into a a file. I am trying to read from this file which contains a string and integers. What is a good way to read to the end of file? I am currently using EOF function but is not working correctly. It repeats the last two lines.

 void viewTransactions();
 void viewTransactions()
{
    string productName,;
    int quantity, totalPrice;

    ifstream infile;
    infile.open ("transactions.txt");
    while(!infile.eof())
    {
    getline(infile, productName);
    infile >> quantity;
    infile >> totalPrice;
    infile.ignore(100, '\n');

    cout << productName << endl;
    cout << quantity << endl;
    cout << totalPrice << endl;


    }
}

"transactions.txt" contains:

Product
1
5
Product
2
10
Product
3
15

Console Output File When Read:

Product
1
5
Product
2
10
Product
3
15

3
15
  • 1
    Can you please provide a sample text file? I mean 2-3 lines of the "transactions.txt". – gsamaras Nov 28 '17 at 06:13
  • @gsamaras I inserted what you asked for, can you take a look plz. – Hugo Canales HAC Nov 28 '17 at 06:32
  • Thanks Hugo. You made a classic mistake, thus I prompted your question to the canonical link. Moreover, @BasileStarynkevitch already suggested a workaround (I didn't check it), thus my work here is done. Good luck! =) – gsamaras Nov 28 '17 at 06:34

1 Answers1

0

infile.eof() is valid only after a read operation (not "before"). And std::getline can set the eofbit, so better code:

for(;;) {
  getline(infile, productName);
  if (infile.eof()) break;
  infile >> quantity;
  infile >> totalPrice;

etc... (or use a do ... while(!infile.eof()) loop).

There is a reason for that (at least on POSIX e.g. Linux): there is no way, at the OS level (i.e. using system calls listed in syscalls(2)) to magically test that EOF condition, it is a result of some previous read(2) operation.

BTW, you probably should compile with all warnings and debug info (g++ -Wall -Wextra -g with GCC). Then use the debugger gdb and you'll have found that bug yourself.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547