Correctly opening txt file and usage

Below i have attached my current project for class and it is compiling fine, it just won't open the txt file titled "in06.txt". I have created the txt file. I am currently in a project that takes the txt file and uses those numbers to make a running count, minimum value, maximum value, and the average of every number on each line separately. After it calculates that, it needs to be set into an output file. Help would be greatly appreciated! Thanks!

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
55
56
57
58
59
60
61
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main()
{
	ifstream fin;
	ofstream fout;

	fin.open ("in06.txt");
	if (fin.fail ());
	{ 
		cout<< "The input file failed to be opened.\n";
		exit (1);
	}

	fout.open ("out06.txt");
	if (fout.fail ());
	{
		cout<< "The output file failed to be opened.\n";
		exit (1);
	}

int count;
double min_val, max_val, average, sum, next_number;
char next_symbol;
	
	fout.setf(ios::fixed);
	fout.setf(ios::showpoint);
	fout.precision (2);

	while (fin>>next_number)
	{	sum+=next_number;
		count++;

		if (count==1) //Performs max/ min assignment
		max_val = min_val = next_number;
		else if (next_number < min_val) 
			min_val = next_number;
		else if (next_number > max_val) 
			max_val = next_number;

		average= sum/count;
	

		fin.get(next_symbol);

		if (next_symbol == '\n') // outputs this only if new line character appears
		{	fout<< "Count: " << count << ", Minimum: " << min_val << ", Maximum: " << max_val << ", Average: " << average << endl;
		count = sum = 0;
	
		}	
	}
	fin.close();
	fout.close ();

	cout<< "The results have officially been written into the output file.\n\n";

	return 0;
}

Your problem is the following line:
 
if (fin.fail ());

The ; should not be there. That causes the if statement to be a no-op.
Therefore the following cout and exit are executed unconditionally.
You have the same problem with line 19.
Also what happens is there is no new line character in your file?

And in C++ programs you should not use the exit() function except in very rare cases. This C function doesn't properly call C++ class destructors which can cause problems.

Thanks. Unfortunately i am having another problem with the program. It doesn't correctly keep track of the count, minimum or average. With in06.txt, i entered 1 2 3 2 1. In the output file it createts count: 671664133 min: 0 average: 0
Where do you initialize count? Where do you initialize sum?

Topic archived. No new replies allowed.