i cant open text file
Aug 4, 2014 at 4:36pm UTC
im unable to open my text file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
char u;
int id, yrs, ctra;
double discount, charge, totdis, fee;
ctra = 0;
totdis = 0;
ifstream infile;
infile.open("TextFile1.txt" );
if (!infile)
cout << "Unable to open file " << endl;
else
{
cout << setw(15) << " ID " << setw(15) << " Type " << setw(15) << " Fee($) " << setw(15) << " Discount($) " << setw(15) << " Charge($)" ;
while (!infile.eof())
{
infile >> id >> u >> yrs;
if (infile.fail())
break ;
else
{
if ( u == 'A' )
fee = 30.00;
else if (u == 'B' )
fee = 150.00;
else
fee = 300.00;
}
if (yrs < 2)
discount = 1 * fee;
else if ( yrs <= 5)
discount = 0.05 * fee;
else
discount = 0.08 * fee;
totdis = totdis + discount ;
charge = fee - discount;
if (u == 'A' )
ctra++;
cout << setw(15) << id << setw(15) << u << setw(15) << fee << setw(15) << discount << setw(15) << charge;
}
cout << " No of Type A members = " << ctra << endl;
cout << " Total discount = " << totdis << endl;
}
infile.close();
system("pause" );
return 0;
}
Aug 4, 2014 at 4:42pm UTC
If your open is failing, then your input file is probably not in the right place.
Since you're using an unqualified file name (textfile1.txt), it should be in the same directory as your executable.
Aug 4, 2014 at 4:49pm UTC
ID Type Fee($) Discount($) Charge($)
1001 A 30 1.5 28.5
1002 A 30 30 0 1003
B 150 7.5 142.5 1004
B 150 7.5 142.5 1005
B 150 12 138 1006 B
150 12 138 1007 C
300 300 0 1008 C
300 15 285 1010 A 30
1.5 28.5 1011 A 30
1.5 28.5 No of Type A members = 4
Total discount = 388.5
Press any key to continue . . .
why is my output like that
Aug 4, 2014 at 4:58pm UTC
why is my output like that
You just need an
endl
in your
cout
statement.
It's not a good idea to loop on eof(). Other errors may occur meaning the eof flag is never set.
Instead of this:
1 2 3 4 5
while (!infile.eof())
{
infile >> id >> u >> yrs;
if (infile.fail())
break ;
it is better to do this:
1 2
while (infile >> id >> u >> yrs)
{
Topic archived. No new replies allowed.