Writing an array from a file

I'm trying to write an array from a file. I'm able to output the numbers that are in the file but when I check to see if the array is populated correctly it instead shows that the whole array is populated by the last number from the file. I'm pretty sure there's something off with my for loops but I'm not sure.

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
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <cmath>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

int main() {
	int i;
	ifstream inputFile;
	string prefix = "H:\\Visual Studio 2017\\Projects\\Data Files\\";
	string datafile;
	string filename;
	double number;
	double array1[1000];
	double MAX_SIZE = 1000;
	

	cout << "Please enter a file name: ";
	cin >> datafile;

	filename = prefix + datafile;
	inputFile.open(filename);

	// If file open successfully, then continue
	if (!inputFile.fail()) {
		// Read the numbers from the file and display them.  Bypass any whitespace
		while ((inputFile >> ws) && (!inputFile.eof()))
		{
			inputFile >> number;
			cout << number << endl;

		}

		// Close the file.
		inputFile.close();
	}
	else {
		cout << "Cannot open file " << datafile << " Aborting." << endl;
		exit(1);
	}
	for (i = 0; i <= number; i++) {
		array1[i] = number;
	}
	for (i = 0; i <= number; i++) {
		cout << "The array at " << i << " is " << array1[i] << endl;
	}
	}
You're going through the whole file, reading each value one at a time into number. At the end of that loop, number will contain the last number. Then in a separate loop, you assign number to every element of array1. You even, strangely, use number as the limit of the loop to fill and display the array.
1
2
3
4
5
6
7
8
9
10
11
12
ifstream inputFile(filename);
if (!inputFile) {
    cout << "Cannot open file " << datafile << " Aborting." << endl;
    exit(1);
}

int size = 0;
while (inputFile >> number)  // >> skips whitespace by default
    array1[size++] = number;

for (int i = 0; i < size; i++)
    cout << array1[i] << '\n';

Last edited on
Topic archived. No new replies allowed.