fin.fail

Hello, I am trying to read a file and take the average of the sum of grades and display the average. I am able to do that just fine, but I am just trying to figure out how to error check. If there is more or less than 10 grades in the file I am pulling from I want it to say "Error reading file from" fileName, but I am having a hard time understanding the syntax of the fin.fail? Where would I put the condition, before the statement "Error reading... " Here is my code below, sorry I tried to search for this but I feel like everything is just fin.fail() and it seems like that's just such a general statement and I just want to know how the computer knows when it should fail opening the file.

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
  int main()
{
   char fileName[256];

   cout << "Please enter the filename: ";
   cin >> fileName;

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

   float sum = 0;
   float numGrades = 0;
   float x;
   float numAverage;

   while (fin >> x)
   {
      numGrades++;
      sum += x;
   }

   numAverage = sum / numGrades;

   cout.precision(0); // round correctly
   cout.setf(ios::fixed); // no scientific notation

   cout << "Average Grade: " << numAverage << "%" << endl;
   return 0;
}
std::ios::fail() isn't really used for what you think it's used for, I don't think. Your arbitrary restriction on how many lines a "valid file" should have has no bearing on whether or not the stream is in a certain state or not.

For what you're trying to achieve, you can simply read the file line-by-line. Push each line onto a vector, then compare the size of the vector against some desired, fixed size.

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
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main() {

	std::string filename = "data.txt";

	std::ifstream stream(filename, std::ios::binary);
	if (!stream) {
		return 1;
	}

	std::vector<std::string> lines;

	std::string current_line;
	while (std::getline(stream, current_line)) {
		lines.push_back(current_line);
	}

	const int number_of_lines = 10;

	if (lines.size() != number_of_lines) {
		//invalid
	}
	
	//parse lines
	
	return 0;
}
Last edited on
Topic archived. No new replies allowed.