/* This program illustrates how to get data in the form of a list of integers from a file and put it into an array. The number of integers in the file is unknown at the beginning, but we assume that it is less than the constant MAX_NUM, which is the number of elements of the array. The program keeps track of the elements of the array and also the number of elements read in from the file (the rest of the slots in the array are not used). It uses the file nums.dat for input data. */ #include #include const int MAX_NUM = 100; /* This is a global variable, the number of elements of the array. As such it must be a const positive integer. */ void get_data(int[], int&); /* Note the syntax for declaring a function in which an array is passed in by value. */ void print_data(int[], int); void main(){ int num_elements; int a[MAX_NUM]; get_data(a, num_elements); print_data(a, num_elements); } /* The function get_data reads the integers stored in the file "nums.dat" into the array a. Notice that even though the array a is passed by value, the function is able to change the elements of a. Also notice the use of the function eof(), which is a function member of the class ifstream. It tests to see if the end of the file has been passed yet. The loop variable n is used to return the number of elements read into the array. If nums.dat contains only two elements such as 5 3 trace through the loop carefully to show that when the function returns (i.e. hits the final }), n is 2, which is of course the number of elements read into the array. */ void get_data(int a[], int& n){ ifstream infile("nums.dat"); for (n=0; n < MAX_NUM; n++){ // Note that the test expression infile >> a[n]; // uses <, not <=. This is since if (infile.eof()) // the last element of a is break; // a[MAX_NUM - 1]. } infile.close(); } void print_data(int a[], int n){ cout << "Here are the elements of the array:" << endl; for (int i=0; i < n; i++) cout << " " << a[i]; cout << ".\n"; }