txt file to array, then output the txt file, then calculate the mean

Can anyone help please?
Read the following number from Input.txt : 1 2 3 4 5 6 7 8 9 10 and keep it as array.
Then display the array to external file called Output.txt
Then find the mean.

1
2
Input.txt
1 2 3 4 5 6 7 8 9 10


My code:

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
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	int z[10]{}, i , c;
	cout << "Enter 10 numbers" << endl;
	ifstream ifp;
	ifp.open("Input.txt");
	for ( i = 0; i <= 9; i++)
	{
		cin >> c;
		z[i] = c;
		ifp >> z[i];
	}
	ifp.close();
	
	ofstream ofp;
	ofp.open("Output.txt");
	for ( i = 0; i <= 9; i++)
	{
		ofp << z[i] << endl;
	}
	ofp.close();

	double sum = 0, mean;
	sum += z[i];
	mean = sum/10;
	cout << "Mean = " << mean << endl;

	
    cin.get();
}


The output is super small number
Last edited on
Try printing out sum as well as Mean on line 30.

Input.txt
1 2 3 4 5 6 7 8 9 10


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

using namespace std;

int main()
{
    int z[10];
    
    ifstream InFile("Input.txt");
    if (!InFile) // some error checking wouldn't hurt
        cerr << "Failed to open input file" << endl;
        
    // supposing that the input file contains 10 space seperated numbers
    for (int i = 0; i <= 9; i++)
    {
        InFile >> z[i]; // read the next integer from the stream
    }
    
    InFile.close();
    
    ofstream OutFile("Output.txt");
    if (!OutFile)
        cerr << "Failed to open output file" << endl;
        
    for (int i = 0; i <= 9; i++)
    {
        OutFile << z[i] << " ";
    }
    
    OutFile.close();
    
    int sum = 0;
    for (int i = 0; i <= 9; i++)
    {
        sum += z[i];
    }
    cout << "Mean = " << sum / 10.0f << endl;
    
    cin.get();
}
Last edited on
@fewdiefie
Your program "checks" for errors opening the file, but then proceeds to read/write the file anyway even if there were any errors. I assume this is not what you wanted.

OP, there is a simpler way of doing what you needed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <fstream>
#include <numeric>
#include <iterator>

int main()
{
    std::ifstream inputFile{"inputfile.txt"};
    std::ofstream outputFile{"outputfile.txt"};
    int arr[10] = {0};
    
    if(inputFile && outputFile) 
        for(int i = 0; inputFile >> arr[i]; i++) outputFile << arr[i] << " ";
    else {std::cerr << "Unable to open file\n"; return 0;}

    std::cout << "The Mean is: " <<
                std::accumulate(arr, arr+std::size(arr), 0.0) / std::size(arr) << std::endl;
}


std::size is from C++17. Let me know if you have any further questions
Last edited on
@jlb

It shows xxE-18 something like this, super duper small number.

@fewdiefie

Thank you so much, it really help me to understand the concept.

@TheToaster

It works fine! So when we put ifstream ofstream in a if statement we wouldn't need to close the file ?
The fstreams can be converted and be used in boolean expressions.

Also, the fstream destructors will automatically close the file. You don't need to call "close" on it specifically if you don't need to open any other files using that filestream. If you wanted, you could call "close" right before outputting the mean, but in this case for such a simple program, there are no resources being wasted by just letting the destructors do their job and having the file remain open for the entirety of the program's lifetime.
Last edited on
It shows xxE-18 something like this, super duper small number.

That looks like you're trying to use an uninitialized variable somewhere.

1
2
3
	double sum = 0, mean;
	sum += z[i];
	mean = sum/10;


Look at the above code. Do you realize that you're only attempting to add one and only one value to sum? What's worse is that the one value you're trying to sum is probably out of the bounds of your array. What is the value of the variable i at that point?

I hate it when teachers tell students to store statistical data in an array. It's unnecessary and limits the number of items. You don't even need to store them to compute standard deviation.

So what if inputfile.txt has 12 items? Or 200? Or 175 million?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>

int main()
{
    std::ifstream inputFile{"inputfile.txt"};
    std::ofstream outputFile{"outputfile.txt"};
    double sum{};
    int count{}, num;

    if(inputFile && outputFile) {
        while (inputFile >> num) {
            outputFile << num << ' ';
            sum += num;
            ++count;
        }
        std::cout << "Mean = " << sum / count << '\n';
    } else {
        std::cerr << "Unable to open file\n"; return 0;
    }
}



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
   ifstream in( "input.txt" );
   ofstream out( "output.txt" );
   int count = 0, sum = 0;
   if ( in && out )
   {
      copy_if( istream_iterator<int>{ in }, {}, ostream_iterator<int>{ out, " " },
         [ &count, &sum ] ( int num ){ count++; sum += num; return true; } );
      cout << "Mean = " << (double)sum / count;
   }
   else
   {
      cerr << "File problems\n";
   }
}
@lastchance not a good idea to show such code to beginners
@lastchance
OP specifically asked for a program that inputs the values into an array and then outputs it to the output file. If those were requirements for an assignment, they should be followed on the dot, otherwise it will not receive credit.
Last edited on
@lastchance I think you wrote copy_if but wanted transform.

fewdiefie wrote:
[It's] not a good idea to show such code to beginners

This seems totally backward to me.

There is a lot to learn from such an example if it is carefully studied. It probably isn't going to be fully understood, but exposure to the idioms in @lastchance's answer are valuable intrinsically.
A few questions that might be raised by lastchance's post include
- what is cerr
- what's going on at line 15?
- where are the files opened
- why wasn't the stream explicitly closed?
- ...
Not to mention the obvious questions (what's copy_if / that iterator stuff), or the small revelation that occurs when a student realizes they can pass functions to other functions.
Last edited on
Thanks @mbozzi, "transform" would have been much more natural than "copy_if" here.

@TheToaster, I wasn't intending to aid the OP to get credit. I was fiddling around with the problem for my own amusement. I'm slightly surprised by what I got away with here, but I'll store it away for a time when it might come in useful.

@fewdiefie ... heaven forbid!
Last edited on
I actually agree with fewdiefie. Dropping code like this on a beginner is likely to leave them hopelessly confused. Sure these are things that need to be learned, but when a student is struggling to understand a for loop, this sort of code probably won't teach them anything.

It's cool code for sure though.
Topic archived. No new replies allowed.