read input and output file using functions in C++

Using functions to read input and output file

Page 1 of 1

2 Replies - 3495 Views - Last Post: 30 January 2010 - 10:42 PM Rate Topic: -----

#1 ccyndimolina  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 16-January 10

read input and output file using functions in C++

Posted 30 January 2010 - 09:22 PM

#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;
	}
}









Is This A Good Question/Topic? 0
  • +

Replies To: read input and output file using functions in C++

#2 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: read input and output file using functions in C++

Posted 30 January 2010 - 10:01 PM

What problem(s) are you having?
Was This Post Helpful? 0
  • +
  • -

#3 seeP+  Icon User is offline

  • D.I.C Addict

Reputation: 55
  • View blog
  • Posts: 601
  • Joined: 20-July 09

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.

This post has been edited by seeP+: 30 January 2010 - 10:43 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1