Question about arrays and external input files

Hi,

I'm writing a program that needs to load 20 integers into an array from an external input file then print the contents of the array in tabular format. I understand how to declare and initialize an array as well as how to print in tabular format etc. The thing I'm unclear about is how to initialize the array i.e. load the integers from with in the external file into the array. I am able to print each element but the value its giving me looks like different memory values. Any help would be appreciated, this is also my first post so please let me know if I posted in an incorrect format, thanks.

My code is below

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 <fstream>
#include <iomanip>
using namespace std;

void loadIt(int[],int);//loadIT prototype

int main()
{	
	ofstream outfile("C:\\CS 201 Data\\P8outdata.txt");
	if (!outfile){
	cerr << "Output file could not be opened" << endl;
	exit(1);}

	outfile << setiosflags(ios::fixed|ios::showpoint);
	outfile << setprecision(3);
	outfile << setiosflags(ios::fixed|ios::showpoint);
	outfile << setprecision(3);
	
	const int arraySize = 20;
	int a[arraySize];
	

	 loadIt(a, arraySize);//call to loadIT
	
}


	//loadIT definition
	void loadIt(int b[], int size)
	{	
		ifstream infile("C:\\CS 201 Data\\P8data.txt");
		if(!infile){
		cerr << "Input file could not be opened" << endl;
		exit(1);}	
		
		infile >> b[size];
		cout << "Element " << setw(12) << "Value " << endl;
		for(int j = 0; j < size; j++)
		cout << setw(6) << j << setw(12) << b[j] << endl;
		
		
		
					  	
		infile.close();
	
		
	}


Try to replace this:
 
infile >> b[size];


with:

1
2
3
for (int i = 0; i < size; i++) {
   infile >> b[i];
}
Thank you very much, that worked, cant believe it was that simple. Thanks again
Topic archived. No new replies allowed.