Oct 6, 2008 at 6:28am UTC
I wrote a code that reads from a file, "fines.dat", then supposed to output the total fines but then it gives a wrong value. Here's the file:
KAB 245K 800.25
KAK 129N 225.50
KAS 176Q 750.00
KAR 231R 75.55
KAB 867V 657.35
KAT 781G 899.00
KAQ 534K 756.45
And here's my code:
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
int main ()
{
string license, numberPlate;
double ticketFines;
double totalFines = 0.0;
ifstream infile;
infile.open("fines.dat");
if(infile.fail())
{
cout<<"File does not exist!";
return 0;
}
getline (infile, license, '\t');
getline (infile, numberPlate, '\t');
infile>>ticketFines;
while(infile)
{
cout<<license<<setw(4)<<numberPlate<<setw(4)<<ticketFines<<endl;
getline (infile, license, '\t');
getline (infile, numberPlate, '\t');
infile>>ticketFines;
totalFines = totalFines + ticketFines;
}
cout<<fixed<<showpoint;
cout<<setprecision(2)<<totalFines<<endl;
infile.close();
return 0;
}
Oct 6, 2008 at 6:55am UTC
I think I found where the problem was. Sorry if I bothered you. Here's my corrected code.
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
int main ()
{
string license, numberPlate;
double ticketFines;
double totalFines = 0.0;
ifstream infile;
infile.open("fines.dat");
if(infile.fail())
{
cout<<"File does not exist!";
return 0;
}
while(infile)
{
cout<<license<<setw(4)<<numberPlate<<setw(4)<<ticketFines<<endl;
totalFines = totalFines + ticketFines;
getline (infile, license, '\t');
getline (infile, numberPlate, '\t');
infile>>ticketFines;
}
cout<<fixed<<showpoint;
cout<<setprecision(2)<<totalFines<<endl;
infile.close();
return 0;
}