Random number calculations Read from/Writing to a file

For context here is what I'm supposed to do...

Write a program that generates a list of random numbers of type int and output to a file named randoms.txt. Then opens the file random.txt, takes its input from the file of numbers of type int and outputs the largest and the smallest number found in the file to the screen.
The program reads all the numbers from the file, and calculates the following:

A) The number of numbers in the file
B) The sum of all the numbers in the file (a running total)
C) The average of all the numbers in the file

Here is what I have so far...

#include<iostream>
#include<cmath>
#include<fstream>
#include<cstdlib>
#include<ctime>
using namespace std;

void analyze(int & number, ofstream & infile, int & sum, int & large, int & small, int & average,int & total_num,float & max)//where the calculations happen
{
//largest to smallest


}

int main()
{
int sum, large, small, average, total_num;


ofstream infile;
infile.open("random.txt");//opens the text file in the folder of the program alongside the cpp file

if (infile.fail())
{
cerr << "Error opening file" << endl;//if there are any errors opening the file it exits the program
exit(1);
}

else {
srand(time(0));
for (int i = 0; i < 100; i++)
{

int number = rand() % 100 + 1;
analyze(number, infile, sum,large,small,average,total_num,max);//this messanges back up to the top void function
}
cout << "Exporting" << endl;
}
infile.close();//closes the file then open up the text file to get random numbers


}

What I am stuck on is how to get letter A-C from the directions. I got the structure done, but how can you get all this from random numbers? I looked everywhere, but it didn't help much. I'm still trying to figure this out on my own, but I would like tips. Thanks in advance.

Last edited on
Hello Deadweight77,

To start with:


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.


While I load the program to read it better and give it a test I did notice the variable "average" may work better as a "double". With integer division any decimal part is lost and you may want that.

The line if (infile.fail()) can be shortened to just if (!infile) and the else part is not needed because of the exit (1); which should be return 1; since it is in main. Use "exit (1)" when this is in another file or another function in "main".

Your "srand" works, but a more proper way to write this is srand(static_cast<size_t>(time(nullptr)));. You could use "unsigned" in place of "size_t". The point is that "srand" takes an "unsigned int" for its number an "time" does not return an "unsigned int".

That is what jumped out for now. I will have some other ideas shortly.

Hope that helps,

Andy
Line 20: Why are you calling your output file "infile". Confusing to the reader.

Line 35: You are analyzing the numbers as you generate them. The instructions say to open the file and read the numbers from the file. You want to analyze the numbers as you read them.

Line 35: max is undefined.

Line 35: You don't actually write the numbers out to the file.

Line 40: You need to open the file for input. Read until you reach eof. Note: Do not do:
while (! infile.eof()). See note below. For each record read, you want to call analyze.

Line 8: You don't want to calculate average inside analyze if analyze is being called for each record. After your read loop, divide sum by total_num to get the average.

Line 8: Not sure what the difference between sum and max is.

Line 8: You don't need to pass infile to analyze() if your read loop is in main.

Line 17: You want to initialize your variables.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

Do not loop on (! stream.eof()) or (stream.good()). This does not work the way you expect. The eof bit is set true only after you make a read attempt on the file. This means after you read the last record of the file, eof is still false. Your attempt to read past the last record sets eof, but you're not checking it there. You proceed as if you had read a good record. This will result in reading an extra (bad) record. The correct way to deal with this is to put the >> (or getline) operation as the condition in the while statement.
1
2
3
  while (stream >> var) // or while (getline(stream,var))
  {  //  Good operation
  }


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

void analyze(int number, int & sum, int & large, int & small, int & total_num)//where the calculations happen
{
    sum += number;
    if (number > large)
        large = number;
    if (number < INT_MAX)
        small = number;
    total_num++;
}

int main()
{
    int sum = 0, large = 0, small = INT_MAX, average, total_num = 0;
    int number;
    ofstream ofile;

    srand(time(0));
    ofile.open("random.txt");//opens the text file in the folder of the program alongside the cpp file

    if (ofile.fail())
    {
        cerr << "Error opening file" << endl;//if there are any errors opening the file it exits the program
        exit(1);
    }
        
    for (int i = 0; i < 100; i++)
    {   int number = rand() % 100 + 1;
        ofile << number << endl;
    }
    ofile.close();//closes the file then open up the text file to get random numbers

    ifstream ifile("random.txt");
    while (ifile >> number)
        analyze(number, sum, large, small, total_num);
    cout << "Largest number is: " << large << endl;
    cout << "Smallest number is: " << small << endl;
    cout << "sum is: " << sum << endl;
    cout << "Average is: " << sum / total_num << endl;
    system("pause");     
}

Last edited on
Thank you both for helping me I'm starting to get it now, but the smallest number isn't right for some reason. I look in the text document to see if I really got the smallest number, but I didn't. Never mind I think I found the problem.
Last edited on
Line 14 should have been:
 
if (number < small)

Yea I figured it out thank you for your help!
Topic archived. No new replies allowed.