// This program demonstrates the passing of a file stream variable to a function. Notice // the use of the & symbol in the function prototype and heading. You need this symbol as // placed. This program also finds the average of each row of 10 numbers from an input // file and outputs the numbers and their averages to an output file. An input file for this // program should have some number of lines with each line containing 10 integers. #include #include #include using namespace std; int openInput(ifstream& fin); int main() { ofstream fout; ifstream fin; char stuff[40]; // used to pick up whitespace at end of line int i, total = 0, x; const int sizeOfData = 10; // the number of values being averaged if (openInput(fin) == 1)// input file not opened return 0; // stop the program fout.open("output.txt"); fout << fixed << showpoint << setprecision(1); while (!fin.eof()) { fout << " Data in: "; for (i = 0; i < sizeOfData; i ++) //sum the ten numbers in the row { fin>>x; fout << setw(3)<< x << ", " ; total += x; } // write out the average for that row fout << ": Average = " << setw(4)<< (double)total / sizeOfData << endl << endl; // reset total for use in next iteration -- easy to forget!!! total = 0; // check for blank spaces at end of line and throw them away fin.getline(stuff,40,'\n'); } return 0; } // Function openInput will try to open a user specified input file, checking // for success. A return value of 1 indicates the file was not opened while // a return value of 0 indicates the file was opened successfully. int openInput(ifstream& fin) { char fname[40]; int bad = 1, good = 0; cout << "Please enter name of input file: " ; cin >> fname; fin.open(fname); if (!fin) { cout << " Could not open input file. " << endl; return bad; } else return good; // open was successful }