精華區beta NTUBA92 關於我們 聯絡資訊
#include <fstream.h> #include <stdlib.h> const int MAXLENGTH = 21; // maximum file name length void openInput(ifstream&); // pass a reference to an ifstream void openOutput(ofstream&); // pass a reference to an ofstream float pollen_update(ifstream&, ofstream&); // pass two references int main() { ifstream in_file; // in_file is an istream object ofstream out_file; // out_file is an ofstream object float average; // display a user message cout << "\n\nThis program reads the old pollen count file, " << "creates a current pollen" << "\n count file and calculates and displays " << "the latest ten week average."; openInput(in_file); openOutput(out_file); average = pollen_update(in_file, out_file); cout << "\nThe new ten week average is: " << average << endl; return 0; } // this function gets an external file name and opens the file for input void openInput(ifstream& fname) { char filename[MAXLENGTH]; cout << "\n\nEnter the input pollen count file name: "; cin >> filename; fname.open(filename); if (fname.fail()) // check for a successful open { cout << "\nFailed to open the file named " << fname << "for input" << "\n Please check that this file exits" << endl; exit(1); } return; } // this function gets an external file name and opens the file for output void openOutput(ofstream& fname) { char filename[MAXLENGTH]; cout << "Enter the output pollen count file name: "; cin >> filename; fname.open(filename); if (fname.fail()) // check for a successful open { cout << "\nFailed to open the file named " << fname << "for output" << endl; exit(1); } return; } // the following function reads the pollen file // writes a new file // and returns the new weekly average float pollen_update(ifstream& infile, ofstream& outfile) { const int POLNUMS = 10; // maximum number of pollen counts int i, polreading; int oldreading, newcount; float sum = 0; float average; // get the latest pollen count cout << "Enter the latest pollen count reading: "; cin >> newcount; // read the oldest pollen count infile >> oldreading; // read, sum and write out the rest of the pollen counts for(i = 0; i < POLNUMS - 1; i++) { infile >> polreading; sum += polreading; outfile << polreading << endl; } // write out the latest reading outfile << newcount << endl; // compute the new average average = (sum + newcount) / (float) POLNUMS; infile.close(); outfile.close(); cout << "\nThe output file has been written.\n"; return average; } -- ※ 發信站: 批踢踢實業坊(ptt.twbbs.org) ◆ From: ntumcc66.mba.ntu.edu.tw