Battling Average

Pages: 12
i was trying like this. can you check if this is correct.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	float atBat = 0, hits = 0, bases = 0;
	int data;
	int i = 0, pos = 0;
	ifstream input("Data.txt");   // this define the "Data" file object and opens Data.txt input file
	//do{
	input >> data; // get input from Data file object
	if (data == -1){
		atBat = atBat + 1;
		hits = hits + 1;
		bases = bases + data; 
	}
	//}while(data != -1 && input);
	cout <<"The batting average for each position was: " << endl;
	while(input >> bases >> atBat >> hits && ++pos)
	{
		cout << "Position " << pos << " batting average is " << hits / static_cast<float>(atBat) << endl;
	}
	
	ifstream input("Data.txt");   // this define the "Data" file object and opens Data.txt input file
	input >> data; // get input from Data file object
	cout <<"\nThe slugging percentage for each position was: " << endl;
	while(input >> hits >> atBat >> bases && ++pos)
	{
		cout << "Position " << pos << " batting average is " << bases / static_cast<double>(atBat) << endl;
	}
	system("PAUSE");
	return 0;
}
1
2
3
4
5
6
7
8
	//do{
	input >> data; // get input from Data file object
	if (data == -1){
		atBat = atBat + 1;
		hits = hits + 1;
		bases = bases + data; 
	}
	//}while(data != -1 && input); 
What is this here for? it does nothing useful.

Also making float atBat = 0, hits = 0, bases = 0; these integer values floats is not really advised.

line 26 input >> data; // get input from Data file object again not needed

Also, on line 25 you are creating another object with the same name as on line 10. You can close the old one and open a new file if you want by doing:
1
2
input.close();
input.open("newfilename.txt");


yes the last option you mention worked:
thank you once again
Topic archived. No new replies allowed.
Pages: 12