This program needs to create a 2D array and store randomly generated integers to it which will be written to a .txt file. The randomly generated numbers need to be stored in ASCII and then converted back to integers in a second program which will use the file created in the first code to find the average of each column in the matrix. This answer needs to be printed in the form of a 1D array. Im still having trouble with the first program, Please help!
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <stdlib.h>
usingnamespace std;
int main() {
cout << "This program will create a multi-dimensional array with random numbers and store it in a file \n\n";
srand((unsigned) time(NULL));
//Asks the users to enter a value between 2 and 50 until they enter a valid value//
cout << "Enter a value between 2 and 50 for the amount of rows: \n";
int rowCount = -1;
while (rowCount < 2 || rowCount > 50)
{
cin >> rowCount;
if (rowCount < 2 || rowCount > 50)
{
cout << "Invalid input, please enter a value that is between 2 and 50 for rows: \n";
continue;
}
}
//Asks the users to enter a value between 2 and 50 until they enter a valid value.//
cout << "Enter a value between 2 and 50 for the amount of columns.\n";
int columnCount = -1;
while (columnCount < 2 || columnCount > 50) {
cin >> columnCount;
if (columnCount < 2 || columnCount > 50) {
cout << "Invalid input, please enter a value that is between 2 and 50 for column: \n";
continue;
}
}
//Creates a new array with row and column count.
int array[rowCount][columnCount];
//Sets a random number value for the entire array row by row, column by column.//
for (int row = 0; row < rowCount; row++)
{
for (int column = 0; column < columnCount; column++)
{
array[row][column] = rand();
}
}
//Asks the user for the file name and checks if they entered any value//
cout << "Enter the file name to store the values of the array.\n";
string fileName = "";
while (fileName.length() < 1)
{
cin >> fileName;
if (fileName.length() < 1)
cout << "Please enter a file name that is valid and ends with .txt\n";
continue;
}
//Creates a file stream for writing data.//
ofstream fileStream;
fileStream.open(fileName);
//Writes all the data from the array to the file.//
fileStream << "[" << rowCount << ", " << columnCount << "]\n";
for (int row = 0; row < rowCount; row++)
{
for (int column = 0; column < columnCount; column++)
{
fileStream << ((char) array[row][column]) << "\t";
}
fileStream << "\n";
}
//Closes the file stream.//
fileStream.close();
return 0;
}
Line 37: change to int array[50][50]; // Note the maximum row/column count
Well, this can be a solution, but it does not seem a problem to me: I think what Avarghese did is just fine. The errors were the file name and the casting to char.