-1

I am trying to figure out how to sum the values generated from a random number generator.

Below my code writes the random number and reads it, and outputs all the random numbers.

I simply cannot figure out how to sum the values generated from the random number.

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>

using namespace std;

class Array
{
public:
    void Arrayoutput()
    {
        string array[1000]; // creates array to hold names
        short loop=0; //short for loop for input
        string line; //this will contain the data read from the file

        ifstream myfile ("Asg4.txt"); //opening the file.

        if (myfile.is_open()) //if the file is open
        {
            while (! myfile.eof() ) //while the end of file is NOT reached
            {
                getline (myfile,line); //get one line from the file
                array[loop]= line;
                cout << array[loop] << endl; //and output it
                loop++;
            }

            myfile.close(); //closing the file
        }
        else cout << "Unable to open file"; //if the file is not open output
    }
};

int main()
{
    Array Array1;
    ofstream myfile;

    myfile.open ("Asg4.txt");

    for (int i = 0; i < 1000; i++) //random number generator
    {
        myfile << 1+(rand()%1000) << endl;
    }
    myfile.close();

    Array1.Arrayoutput();

    return 0;
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
Toni
  • 105
  • 6
  • 3
    First of all, please read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Some programmer dude Feb 09 '19 at 07:42
  • Secondly, you write to the file using `<>`? And why the read strings if the contents are numbers? And for the reading you don't actually need an array of values. – Some programmer dude Feb 09 '19 at 07:43

1 Answers1

2

Here's how to read numbers from a file and add them up

ifstream myfile ("Asg4.txt"); //opening the file.
int total = 0;
int number;
while (myfile >> number)
    total += number;
cout << "The total is " << total << "n";
john
  • 71,156
  • 4
  • 49
  • 68
  • 1
    You could even do away with the manual loop: `int total = std::accumulate(std::istream_iterator(myfile), std::istream_iterator(), 0);` – Remy Lebeau Feb 09 '19 at 09:21