I am working on a project which requires certain actions be in their own functions. Right now, I must take the random values generated, and output them FROM an array. I have the values stored in numarray
, but I don't know how I can call that array in the function to output the values. I have a function set up which seems like it will take the array and output it, but I don't know how to call the function without an argument to pass through it in main
. Is this a possible way to output the array, or is there a completely different way this should be done.
PS: I know namespace isn't good, but it's what I have to do to pass the class.
#include <iostream>
#include <fstream>
#include <time.h>
#include <stdlib.h>
#include <cstddef>
using namespace std;
ofstream randomData;
ifstream inputrandomData;
void randomgenerator();
void read();
void printArray(int *numarray);
void randomgenerator() {
srand(time(0));
randomData.open("randomData.txt");
for (int counter = 0; counter < 100; counter++) {
randomData << rand() % 100+1 << endl;
}
randomData.close();
}
void read() {
inputrandomData.open("randomData.txt");
int numarray[100] = {};
for (int i = 0; i < 100; i++) {
inputrandomData >> numarray[i];
}
inputrandomData.close();
}
void printArray(int *numarray) {
for (int index = 0; index < 100; index++) {
cout << numarray[index];
}
}
int main() {
randomgenerator();
read();
printArray();
return 0;
}
The randomgenerator
function is what makes the values and stores them in a file.
The read
function takes those values and stores them in an array.
printarray
is the function where I want to output the array values, and is giving me the problem.
You need to dynamically allocate and return numarray from read. Or even better create numarray like you did here on the stack, but do it in main and pass it as an argument to read, then pass as an argument to printArray.
As it is numarray will go out of scope when read completes, since your allocating it on the stack.