0

My while loop won't exit while I'm using eof to control when it should stop. The input file contains the price and quantity on the same line, and the next line has the same, but of different prices and quantities.

sum = 0
item = 0
in >> price >> quantity;

while (!in.eof())
{
    item ++;
    total = price * quantity;
    sum = sum + total;
    cout << setw(20) << left << setfill(' ') \
<< item
        << setw(20) << right << setfill(' ')\
 << price
        << setw(20) << right << setfill(' ')\
 << quantity
        << setw(20) << right << setfill(' ')\
 << total
        << endl << endl;

    in >> price >> quantity;
}

The output should show the user each price, quantity and total cost for each item that is in the input file.

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
  • What data is it reading? What output are you getting? What output are you expecting? – David Schwartz Oct 17 '19 at 00:19
  • @alterigel that doesn't apply in this case because the OP is reading from the stream before checking `eof()` – Remy Lebeau Oct 17 '19 at 00:22
  • 2
    This doesn’t address the question, but you don’t need those backslashes. It’s okay for statements to take up more than one line. You only need backslashes for **macro definitions** that are longer than one line. – Pete Becker Oct 17 '19 at 00:24
  • By the way, what's actually going wrong here is probably that the stream is hitting an error condition other than end of file, which there is currently no code to handle. – David Schwartz Oct 17 '19 at 00:31

1 Answers1

0

I would suggest a different approach - read the file line-by-line, parsing each line, eg:

sum = 0;
item = 0;

string line;
while (getline(in, line))
{
    istringstream iss(line);
    if (iss >> price >> quantity)
    {
        ++item;
        total = price * quantity;
        sum += total;

        cout << setw(20) << left  << setfill(' ') << item
             << setw(20) << right << setfill(' ') << price
             << setw(20) << right << setfill(' ') << quantity
             << setw(20) << right << setfill(' ') << total
             << endl << endl;
    }
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620