Reading a dynamically allocated array from a file

Having some trouble getting the output that I want.
The test file that I'm reading from has integers 1, 2, 3, 4, and 5 respectively, each on their own line.

Here's what I need to do:

1: Open the file
2: Count the # of integers in the file
3: Close the file
4: Allocate an array of integers using that count for the size of the array
5: Open the file
6: Read the numbers into the array and sum them all
7: Sort them using bubble sort
8: Print sorted array and average of values

my problem is at step 6. When I'm reading from the file I get an output of:
1
2
3
4
5
5
5
5
5
5

Any help would be greatly appreciated.

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
inFile.open(filename);

	if (inFile.fail()) {
		cout << "\nThe file was not successfully opened"
			<< "\nPlease check that the file currently exists."
			<< endl;
		exit(1);
	}

	while (getline(inFile, line)) {  
		i++;                  //counter for number of integers in file
	}

	inFile.close();

	numOfInt = i;                   
	int *ary = new int[numOfInt]; //allocate memory for new array

	inFile.open(filename);
	inFile.seekg(0L,ios::beg);   //go to beginning of file

	while (!inFile.eof()) {
		for (j = 0; j < numOfInt; j++) {
			inFile >> num;
			ary[j] = num;
			cout << ary[j] << endl;
		}
	}
	
	system("pause");
	return 0;
}
You know already how many integers to read, so don't bother checking for the end of the file.

Make sure there aren't any empty lines at the end of the input file. Empty lines are still lines. The '5' should be the very last character in the file. No lines after it.

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main()
{

  ifstream inFile;
  inFile.open("ints");

  if (inFile.fail()) {
    cout << "\nThe file was not successfully opened"
	 << "\nPlease check that the file currently exists."
	 << endl;
    exit(1);
  }
  string line;
  int i = 0;
  while (getline(inFile, line)) 
  {  
    i++;                  //counter for number of integers in file
  }

  cout << "Number of line: " << i << '\n';

  inFile.close();

  int numOfInt = i;                   
  int *const ary = new int[numOfInt]; //allocate memory for new array

  inFile.open("ints");
  for (int j = 0; j<numOfInt; j++) 
    {
        
      inFile >>ary[j];
      cout << ary[j] << endl;
		
    }
  delete[] ary;
}

Last edited on
Thank you Moschops it worked perfectly!!

I don't know why I didn't just connect the istream object to the array element in the first place..

Do you think that was causing the loop or was it the while !eof statement?
Topic archived. No new replies allowed.