Problem with Text Files

Hi all. I am having some trouble with figuring out how to do something on my program. I am to create a program to read a certain file, and give its average. I have successfully done that, but I am also supposed to creat a fall back just in case it cannot read the file, which I have done. What I am having a problem with is when it says, "Error reading file" and then it also shows "average grade"
ex. Please enter the file name: number.txt
Error reading file "number.txt"
Average Grade 0%

How do I make the program so that it will not have the "Average Grade 0%" when there is an error?

Code Below


#include <iostream>
#include <fstream>
using namespace std;

void getFileName(char fileName[]);
float readFile(char fileName[]);
void display(float average);

int main()
{
char fileName[256];
float average;
getFileName(fileName);
average = readFile(fileName);
display (average);
return 0;
}

void getFileName(char fileName[])
{
cout << "Please enter the filename: ";
cin >> fileName;

return;
}

float readFile(char fileName[])
{
cout.setf(ios::fixed); //no scientific notation
cout.precision(0); //no decimal, but rounds right

//open file
ifstream fin(fileName);
if (fin.fail())
{
cout << "Error reading file \""
<< fileName << "\"" << endl;
return false;
}

float one;
float two;
float three;
float four;
float five;
float six;
float seven;
float eight;
float nine;
float ten;
float average;
float x;
fin >> one >> two >> three >> four
>> five >> six >> seven >> eight
>> nine >> ten;
x = one + two + three + four + five
+ six + seven + eight + nine + ten;
average = x / 10;
return average;
}

void display(float average)
{
cout << "Average Grade: " << average
<< "%" << endl;

return
}
Well, you call the function like this from main(),
average = readFile(fileName);

The function returns the value "average" to main(). Really, you need the function to return two values, the average, and an indication of whether or not the file was successfully read.

If you know for example that average must always be number greater than or equal to zero, you could pass back a special value such as -1.0 to indicate an error occurred. Then test the value, if it's -1, don't display the result.

A more robust solution might be to pass by reference a second parameter to the function readFile, and use that to indicate success or failure.

Another option would be to open the file before you start your calculations possibly in main or a separate function, and if it doesn't open properly stop the program. Then pass a reference to your file stream into your function instead of the file name.
Topic archived. No new replies allowed.