#include <iostream> #include <iomanip> #include <fstream> using namespace std; //Function prototypes void calculateAverage(ifstream& inp, double& avg); void printResult(ofsream& outp, double sum, double avg); int main() { int numberOfNumbers; int num; double avg1; double sum; ifstream numbers; ofstream numbers2; numbers.open("numbers.txt"); if (!numbers) { cout << "Unable to open files." << endl; cout << "Program terminates." << endl; return 1; } numbers2.open("numbers2.txt"); numbers2 << fixed << showpoint; numbers2 << setprecision(2); int num = 0; double sum = 0.0; int numberOfNumbers = 0; numbers >> num; while (numbers) { calculateAverage(numbers, sum); printResult(numbers2, sum, avg); avg1 = avg1 + avg; outfile << endl; numberOfNumbers++; } } numbers2 << "Sum for numbers: " << sum / numberOfNumbers << endl; numbers2 << "Avg for numbers: " << sum / numberOfNumbers << endl; } numbers.close(); numbers2.close(); return 0; } void calculateAverage(ifstream& inp, double& avg) { double sum = 0.0; int numberOfNumbers = 0; int num; inp >> num; while (num != -999) { sum = sum + num; numberOfNumbers++; inp >> num; } }
read input and output file using functions in C++Using functions to read input and output file
Page 1 of 1
2 Replies - 9176 Views - Last Post: 30 January 2010 - 10:42 PM
#1
read input and output file using functions in C++
Posted 30 January 2010 - 09:22 PM
Replies To: read input and output file using functions in C++
#2
Re: read input and output file using functions in C++
Posted 30 January 2010 - 10:01 PM
What problem(s) are you having?
#3
Re: read input and output file using functions in C++
Posted 30 January 2010 - 10:42 PM
You did not define the printResult().
You pass the value of sum to calculateAverage() as a refrence, but your not even using it in that function, which is now named 'avg'. So the referenced value never changes(still 0.0). The sum that you pass to the function is different from the one created in the function. You need to read up on passing values to functions.
You pass the value of sum to calculateAverage() as a refrence, but your not even using it in that function, which is now named 'avg'. So the referenced value never changes(still 0.0). The sum that you pass to the function is different from the one created in the function. You need to read up on passing values to functions.
This post has been edited by seeP+: 30 January 2010 - 10:43 PM
Page 1 of 1