#include #include const int ARRAYSIZE = 40; // the function prototypes void printArr (int[], int, int=5); int readArr (int[], int); main() { int size; // contains how many values are actually // in the array int arr[ARRAYSIZE]; int i; int temp; cout << "Welcome" << endl << endl; cout << "Reading values from the file" << endl; // call a function to read in an array size = readArr (arr, ARRAYSIZE); // call a function to print an array cout << endl << "5 per line" << endl; printArr(arr, size); cout << endl << "8 per line" << endl; printArr(arr, size, 8); cout << endl << "15 per line" << endl; printArr(arr, size, 15); cout << endl << "2 per line" << endl; printArr(arr, size, 2); cout << endl << "Goodbye" << endl; } // The following function will read in values and store them // into an array. // // Parameter 1: the array // 2: the maximum size of the array // Return: the number of values actually stored in the array. int readArr(int arr[], int max) { int i = 0; int fileSize; int temp; // read values into the array (feof) while (cin >> temp) { // verify the number of values read if (i >= max) { cout << "Error: attempted to overfill the array of size " << max << endl; fileSize = i + 1; while (cin >> temp) fileSize++; cout << "File contains " << fileSize << " values." << endl; return i; } arr[i] = temp; i++; } return i; } // The following function will print an array with 5 values // per line as a default. If a third parameter is given, this // parameter will specify the number of value per line. // // Parameter 1: The array // 2: The size of the array // 3: number of value per line (5 by default) // Returns nothing void printArr(int arr[], int sz, int perLine = 5) { int i; // Display the values in the array for (i = 0; i < sz; i++) { // cout << width(5) << arr[i] << " "; cout << arr[i] << " "; if ((i+1) % perLine == 0) cout << endl; } } /* /homes/home30/hkim16/107> a.out < readfile1.dat Welcome Reading values from the file Error: attempted to overfill the array of size 40 File contains 42 values. 5 per line 1 2 3 4 5 6 7 8 9 0 7 8 4 9 5 1 7 8 4 0 2 3 8 1 5 6 3 9 2 3 2 3 4 2 6 2 7 8 9 0 8 per line 1 2 3 4 5 6 7 8 9 0 7 8 4 9 5 1 7 8 4 0 2 3 8 1 5 6 3 9 2 3 2 3 4 2 6 2 7 8 9 0 15 per line 1 2 3 4 5 6 7 8 9 0 7 8 4 9 5 1 7 8 4 0 2 3 8 1 5 6 3 9 2 3 2 3 4 2 6 2 7 8 9 0 2 per line 1 2 3 4 5 6 7 8 9 0 7 8 4 9 5 1 7 8 4 0 2 3 8 1 5 6 3 9 2 3 2 3 4 2 6 2 7 8 9 0 Goodbye /homes/home30/hkim16/107> */