-
Help with loop
The while loop does an extra iteration, and I don't know why. E.g. if there are only 2 lines in the file it is reading, it prints out the last price and quantity twice, and adds their product to sub. I think it prints out whitespace before that.
fin is an ifstream object. If I change the while condition to (!EOF), the file is not read at all.
I suspect that it has something to do with getline (fin, prodDesc), but prodDesc is a string that may contain spaces, so I don't know how else to read it in.
Any suggestions? My head is swimming.
-->Mariana
Code:
//this is part of a program that reads from a file
// and outputs a billing invoice
void processOrder(float&sub)
{
sub=0;
do
{
fin>>code>>price>>quantity;
getline (fin, prodDesc);
total = price * quantity;
cout<<fixed<<showpoint<<setprecision(2)
<<setw(20)<<left<<code
<<setw(20)<<left<<prodDesc
<<setw(15)<<price
<<setw(15)<<quantity
<<setw(15)<<total;
sub += total;
}while(fin);
cout<<setw(30)
<<"Total order: $"
<<setprecision(2)
<<setw(15)
<<fixed<<showpoint
<<sub<<endl;
}
-
A variation of the eof() problem discussed in the FAQ
Try
Code:
while ( fin>>code>>price>>quantity ) {
getline (fin, prodDesc);
total = price * quantity;
cout<<fixed<<showpoint<<setprecision(2)
<<setw(20)<<left<<code
<<setw(20)<<left<<prodDesc
<<setw(15)<<price
<<setw(15)<<quantity
<<setw(15)<<total;
sub += total;
}
-
Thank you!
I actually asked a friend for help, and we ended up using the return value of getline() to break it up.
Code:
//Reads from file, calculates subtotal
void processOrder(float&sub)
{
sub=0;
do
{
fin>>code>>price>>quantity;
if (getline (fin, prodDesc) != 0)
{
total = price * quantity;
cout<<fixed<<showpoint<<setprecision(2)
<<setw(10)<<left<<code
<<setw(20)<<left<<prodDesc
<<setw(10)<<right<<price
<<setw(15)<<quantity
<<setw(15)<<total<<endl;
sub += total;
}
}while(fin);
cout<<setw(55)
<<"Total order: $"
<<setprecision(2)
<<setw(15)
<<fixed<<showpoint
<<sub<<endl;
}