Question: why does it print out the correct values inside the while loop (while reading / inputting the file) but not outside the while loop? I don't understand. Thank you very much for any help.
input file:
1
2
3
4
5
#include <iostream>
#include <string>
#include <fstream>
#include <string>
using namespace std;
int sumNumbers(int sum, int* numbers, int numElements, int count)
{
if (count == numElements) return sum;
sumNumbers(sum + numbers[count], numbers, numElements, count + 1);
return 0;
}
int main(int argc, char* argv[])
{
int* numbers;
int numElements = 0;;
int sum = 0;
string fileName = argv[2];
ifstream ifile(fileName);
if( ifile.fail() ) {
cout << "The file could not be opened. The program is terminated." << endl;
return 0;
}
while ( !ifile.eof() ) {
numbers = new int[++numElements];
ifile >> numbers[numElements - 1];
cout << "Position " << numElements - 1 << ": " << numbers[numElements - 1] << endl;
}
cout << numbers[0] << endl;
cout << numbers[1] << endl;
cout << numbers[2] << endl;
cout << numbers[3] << endl;
cout << numbers[4] << endl;
cout << "--------------\n";
for(int i = 0; i < numElements; i++) {
cout << "Position " << i << ": " << numbers[i] << endl;
}
sumNumbers(sum, numbers, numElements, 0);
cout << "The sum of the numbers in the file is: " << sum << endl;
return 0;
}
output:
Position 0: 1
Position 1: 2
Position 2: 3
Position 3: 4
Position 4: 5
0
-805306368
0
-805306368
5
--------------
Position 0: 0
Position 1: -805306368
Position 2: 0
Position 3: -805306368
Position 4: 5
The sum of the numbers in the file is: 0