So i made a program that fills an array with random numbers and then puts those random numbers into a txt file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
ofstream outputFile;
unsigned seed = time(0);
srand(seed);
int numList[100];
for(int i=0; i < 100; i++)
{
numList[i] = rand()%100+1;
}
outputFile.open("NumbersWrite.txt");
for(int i=0; i<100; i++)
{
outputFile << numList[i];
}
return 0;
}
|
Then i made a second program that's supposed to read the numbers from the txt file and put them into an array and calculate the total and average.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int printElements(int array[]);
int main()
{
int total;
int average;
ifstream in;
int array[100];
int i=0;
in.open("NumbersWrite.txt");
while(! in.eof())
{
in >> array[i];
i++;
}
total = printElements(array);
average = total / 100;
cout << "Total: " << total << "\n";
}
//*******************************************************
int printElements(int array[])
{
int total = 0;
int i = 0;
cout << "\n\n";
for (i=0; i<100; i++)
{
cout << array[i] << ",";
total = total + array[i];
}
cout << "\n\n";
return total;
}
//********************************************************
|
but for some reason the second program gives me the output
2147483647,4703424,4206395,4661576,-1,2686332,761488231,4661576,4705684,6,466032
8,0,2686524,2,4705684,0,4660328,2686696,4251833,0,6,4661576,4705684,4660328,4705
684,2686428,4290022,4640780,2686524,1,4705684,6,0,6,16,1,4200860,4635612,4683024
,4682916,0,2686696,0,7933560,7933560,2686568,1987835008,7929856,0,1987835017,-42
7065163,16,7933576,7933560,2001271530,2001408146,-1,36,0,7933560,7933560,2686632
,1987835008,7929856,0,1987835017,-427065227,20,7933580,7933560,2001271530,200140
8146,-1,36,2686616,4,0,-458310117,2686632,1987835392,0,0,0,2686652,1987814466,19
88428456,2686716,1987835090,8,1987842446,1987842402,-427065311,0,0,0,4286272,268
6672,2686728,2686916,1987939541,
Total: 1192635174
Process returned 0 (0x0) execution time : 0.080 s
Press any key to continue.
The numbers look nothing like the one's in the text file.
Could you explain why and how to fix it
any help would be greatly appreciated.