I want to generate a random array.
void Random_nums(int n, string fileName) {
ofstream fsave(fileName);
int ranArray[n];
srand( (unsigned int)time(NULL) );
for(int i=0; i<n; i++)
{
ranArray[i]=rand()%2001 - 1000;
fsave << ranArray[i] << '\n'; //save them into ranArray
}
fsave.close();
}
And I want to save them into a separate file.
After that I want to read the data I just saved and implement them in a new function.
void FunctionWantToUse(string inputFile, string outputFile) {
//reading data
ifstream fin(inputFile);
cout << fin.is_open();//which is 1
//how many numbers are there in this file
int n = 0;
n = distance(istream_iterator<int>(fin), istream_iterator<int>());
//restore the array
int array[n];
//test
cout << fin.peek() << ' ' << EOF;//they are both -1!
//another test
cout << fin.peek() << '\n'; //which return -1
cout << fin.eof() << '\n'; //which return 1
//since peek() and EOF both return -1, I can't get into this loop.
while (fin.peek() != EOF) {
if ((fin >> array[i]).good()) {
cout << array[i];
}
}
Completely have no idea why the value of fin.peek() and fin.eof() change to -1 and 1 respectively.
And the console told me this as I run these two functions.
-1 -1-1
1
Process finished with exit code 0
I also give some other tests, such as, place fsave.eof() in the loop when I generate random number, and it prints out all 0s.
Could someone please tell me what's going on here? I completely have no clue right now.