-

2011年8月3日星期三

How can I make this C++ code read from a .dat file?

-This program total ups how much money someone makes before taxes.

I just need it to read the values from a file and save them in a file

This assignment is due tonight and i'm not sure how to do it, any help would be great





Here is my code:

#include <iostream>

#include <iomanip>



using std::cout;

using std::cin;

using std::endl;

using std::fixed;

using std::setprecision;



int main()



{



double hours = 40.0;

double rate = 10.0;

double gross = 0.0;

double overtime = 1.5;





cout << "Enter the ammount of hours worked: ";

cin >> hours;

cout << "Enter the ammount paid per hour: ";

cin >> rate;



if (hours<0 || rate<0)



cout << "ERROR pick a different number" << endl;



else



if(hours > 40){ //calculate gross pay

overtime = (hours-40) * rate * 1.5;

gross = 40 * rate + overtime;



}



else

{

gross = rate * hours;

}



cout << "Overtime: " << overtime << endl;

cout << "Gross pay: " << gross << endl;



system ("pause");



return 0;



}The include file <fstream> has classes for streams for reading from and/or writing to named files. In particular ifstream and ofstream are specifically input and output streams, respectively. Here's a trivial example:



#include <iostream>

#include <fstream>



using namespace std;



int main()

{

ifstream fin("input.txt");

float a,b;

fin >> a >> b;

ofstream fout("output.txt");

fout << a << " + " << b << " = " << (a+b) << endl;

fout.close();

}



Given a text file "input.txt" with "23 19" in it, this produces an output file with "23 + 19 = 42" as its only line.



Your logic will have to change some. After all, you can't really prompt a disk file, or tell it to retry on badly-formatted input. It contains usable data or it doesn't. So, if there's a problem you simply write an error message to cout or cerr, and then exit...usually with a nonzero return value from main().



The only reason to do a close explicitly, by the way, is to test for errors. Even with "endl" forcing buffer writes--in principle at least--there is some final writing to the file system that happens on an output file when it is closed. It's only when this returns good status that you are assured the the entire file did, in fact, get correctly written. I obviously left out error checking. I'd use exceptions and try/catch...but I suspect you haven't studied those yet.



Even if you're not checking for I/O errors yet, try to get in the habit of closing output files. Closing input files is also a good thing to do if your program is going to run for any length of time after you finish reading, but before the ifstream object gets destroyed. That frees up resources for other uses.

没有评论:

发表评论