#include #include #include void pause (void) { cout << "Hit any key to continue.\n"; getch(); } // given the name of a file and an array, reads the values in // the file and stores them in the array. returns true if the // operation was sucessfully completed and false otherwise. sets // call by reference parameter "values_read" to the number of // values actually read (posibly zero) bool read_file (char filename[], int n, // size of array double array[], int &values_read) { ifstream fin; double value; fin.open (filename, ios::in); if (fin.fail()) { // file could not be opened return false; } values_read = 0; // nothing read in so far for (;;) { // try and read another value fin >> value;; if (fin.fail()) { // read did not work for some reason if (fin.eof()) { // read did not work because we've hit the end of the file // - everything is fine return true; } else { // read failed for some other reason - we've a problem return false; } } if (values_read == n) { // the array is already full - we have overflow return false; } // store the value into the array array[values_read++] = value; } // we can never get here (therefore no return is required) } double sum_up_elements (double array[], int first, int count) { double sum; int i; sum = 0; for (i = first; i < first + count; i++) { sum += array[i]; } return sum; } int main (void) { const int array_size = 200; char filename[60]; double array [array_size], max_weight, weight; int train_cars, first_car, test_cars, problems; cout << "Enter name of file: "; cin >> filename; if (!read_file (filename, array_size, array, train_cars)) { cout << "Could not read file.\n"; pause(); return 0; } cout << "Enter number of cars and max weight: "; cin >> test_cars >> max_weight; if (train_cars < test_cars) { // a short train - just check that its entire weight is less // than the maximum allowable weight weight = sum_up_elements(array, 0, train_cars); if (weight > max_weight) { cout << "The train is short but too heavy (" << weight << " tons).\n"; } else { cout << "No problems detected.\n"; } pause(); return 0; } problems = 0; for (first_car = 0; first_car <= train_cars - test_cars; first_car++) { weight = sum_up_elements(array, first_car, test_cars); if (weight > max_weight) { cout << "Cars " << (first_car + 1) << " through " << (first_car + test_cars) << " exceed the maximum weight (weight = " << weight << " tons).\n"; problems++; } } cout << "Number of problems detected: " << problems << endl; pause(); return 0; }