mercredi 3 mars 2021

Writing random data to a text file c++

I am creating a program that generates a given number of rows of random data, each row has 10 random int values from -50 to 50. The final column is the sum of row values.

I am having trouble writing the random data to a text file. The final column seems to be the only issue when I run it.

I am new to this, so please bear with me.

So far, this is my program:

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

//function prototype
void writeData(int, int);

int main() {

    int ROWS;
    const int COLS = 10;

    cout << "Enter number of rows (10-25): ";
    cin >> ROWS;

    writeData(ROWS, COLS);
    return 0;
}//end main


void writeData(int ROWS, const int COLS) {

    //Create an array with column count.
    int arr[ROWS][COLS];
    
    //Seed the random number generator.
    srand((unsigned)time(0));
    
    //Create and open a file.
    ofstream outputFile;
    outputFile.open("myfile.txt");

    //Generate a random number (between 10 and 25) of rows of random data.
    //Write random data to file.
    
    outputFile << "[" << ROWS << ", " << COLS+1 << "]\n";
    
    int sum = 0;
    for(int i=0; i<ROWS; i++) {
        for(int j=0; j<COLS; j++) {
            arr[i][j] = (rand()%50)+(-50);       //each row has 10 random integer values between -50 and 50
            outputFile << ((int) arr[i][j]) << "\t";
            sum += arr[i][j];   //sum row values
        }

        outputFile << arr[i][COLS] << sum << endl;  //store row sum in last column in the row
        sum = 0;   //reset sum to 0
    }
    
    //Close the file.
    outputFile.close();
    
    //Confirm the data is written to file.
    cout << "The data was saved to the file.\n";
}//end writeData

I get this for output:

[10, 11]
-5  -7  -28 -48 -12 -2  -29 -28 -40 -18 0-217
-49 -11 -15 -20 -34 -40 -25 -46 -41 -42 1430822061-323
-3  -13 -27 -24 -13 -29 -44 -25 -43 -2  764375682-223
-43 -37 -32 -40 -26 -29 -30 -32 -22 -24 0-315
-31 -12 -2  -12 -38 -15 -27 -36 -24 -21 71091072-218
-11 -49 -48 -47 -10 -44 -32 -22 -31 -7  -343595632-301
-32 -17 -28 -34 -48 -46 -29 -9  -17 -13 0-273
-22 -46 -25 -3  -34 -14 -2  -32 -7  -22 400-207
-5  -13 -13 -14 -17 -47 -28 -19 -5  -36 10-197
-3  -1  -27 -4  -30 -43 -47 -20 -13 -16 -343595600-204

I have gotten this far by trial and error. Now, I am stuck. Some guidance would be much appreciated.




Aucun commentaire:

Enregistrer un commentaire