I am having trouble opening a file after I close it. It is at the point where I verify the file is open, but it keeps telling me file closed. And just as a side note the stars around the code are not in the actual program. It is just there to easily find what I am talking about. I am using the same code that was used to first open. I would appreciate any and all help here.
//function prototypes
double averageScore(int, int, int);
int highestScore(int, int);
int amountA(int, int);
int main()
{
//Declaring variables
string fileName;
ifstream inputFile;
int test1, test2, test3, students = 5, test1Sum, test2Sum, test3Sum;
int highScore = 0, numberA;
double average;
cout << "Please enter the file you wish to open: ";
cin >> fileName;
//Opening file
inputFile.open(fileName.c_str());
//Displaying average score per student
cout << "Average per student: ";
for (int count = 0; count < students; count++)
{
inputFile >> test1 >> test2 >> test3;
average = averageScore(test1, test2, test3);
cout << setprecision(2) << fixed << showpoint;
cout << count+1 << "=" << average << " ";
}
cout << endl;
//Closing and re-opening file
inputFile.close();
inputFile.open(fileName.c_str());
//Display average per test
double average;
cout << "Please enter the file you wish to open: ";
cin >> fileName;
//Opening file
inputFile.open(fileName.c_str());
//Displaying average score per student
cout << "Average per student: ";
for (int count = 0; count < students; count++)
{
inputFile >> test1 >> test2 >> test3;
average = averageScore(test1, test2, test3);
cout << setprecision(2) << fixed << showpoint;
cout << count+1 << "=" << average << " ";
}
cout << endl;
//Closing and re-opening file
inputFile.close();
inputFile.open(fileName.c_str());
//Display average per test
//Displaying High Score
while (inputFile >> test1)
{
highScore = highestScore(highScore, test1);
}
cout << "The overall highest score is: " << highScore << endl;
//Number of A's
while (inputFile >> test1)
{
numberA = amountA(test1, 90);
}
cout << "There were " << numberA << " number of scores that were an A" << endl;
return 0;
}
//**********************
//Calculating average per student
//*********************
double averageScore (int num1, int num2, int num3)
{
int sum;
double numberTests = 3.0;
sum = num1 + num2 + num3;
return (static_cast<double>(sum) / numberTests);
}
If the stream is already associated with a file (i.e., it is already open), calling this function fails...The function sets failbit in case of failure.
std_ios_operator bool wrote:
Returns whether an error flag is set (either failbit or badbit).
Look through your code to see where you've violated the requirements for open