Reading from a file

I can't seem to open the file as when the program terminates after the user enters the file name.

Write a program that reads a text file. The user will input the file name containing a list of students with their test scores on three tests. For example:

Ana 75 82 91

John 80 93 100

Mary 91 77 92

The program calculates and prints out for each student: their name, the lowest, the highest and the average score. Round the average to the nearest tenth. Create a well-formatted table to display the data on the screen. Print the header only once.

+------------------------------------------------------

| Name Average Lowest Highest

+------------------------------------------------------

[ the output data goes here ]

At the end, the program should print the class average.

This is my code so far:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
double calAverage(double &first,double &second,double &third);
int findHighest(double first, double second, double third);
int findLowest(double first, double second, double third);
int main() {
	ifstream infile;
	string fileName;
	double totalAverage = 0;
	cout << "Enter the file name: " << endl;
	cin >> fileName;
	infile.open(fileName.c_str());
	if(infile){
		string name;
		double score1 = 0;
		double score2 = 0;
		double score3 = 0;
		while (infile >> name >> score1 >> score2 >> score3){
			calAverage(score3, score2, score3);
			findHighest(score1,score2,score3);
			findLowest(score1,score2,score3);
		}
	}
	else
		cout << "Error cannot open file";
	infile.close();
	return 0;
}
// Calculates the average of the numbers in the parameters
double calAverage(double &first,double &second,double &third)
{
	return (first + second + third) / 3.0;
}
// This function determines and returns the highest of the three scores passed as parameters
int findHighest(double first, double second, double third){
	if(first >= second && first >= third)
		return first;
	else if(second >= third && second >= first)
		return second;
	else
		return third;
}
// This function determines and returns the lowest of the three scores passed as parameters
int findLowest(double first, double second, double third){
	if(first <= second && first <= third)
			return first;
		else if(second <= third && second <= first)
			return second;
		else
			return third;
}

Last edited on
1
2
3
4
string fileName;
	double totalAverage = 0;
	cout << "Enter the file name: " << endl;
	cin >> fileName;

use getline(), not std::cin to read strings;
edit: also do have a read up on both getline() and cin to make sure you understand how they treat newline, white-space etc
Last edited on
Topic archived. No new replies allowed.