// File Name: Streams.cpp // Ask the names for the input and output files. // Reads three numbers from the input file, sums the numbers, and writes the // sum to both the screen and the output file specified by the user. #include #include #include int main() { using namespace std; char in_file_name[16], out_file_name[16]; // the filenames can have at most 15 chars ifstream in_stream; ofstream out_stream; cout << "This program will sum three numbers taken from an input\n" << "file and write the sum to an output file." << endl; cout << "Enter the input file name (maximum of 15 characters):\n"; cin >> in_file_name; cout << "\nEnter the output file name (maximum of 15 characters):\n"; cin >> out_file_name; cout << endl; // Condensed input and output file opening and checking. in_stream.open(in_file_name); out_stream.open(out_file_name); if( in_stream.fail() || out_stream.fail() ) { cout << "Input or output file opening failed.\n"; exit(1); } double firstn, secondn, thirdn, sum = 0.0; cout << "Reading numbers from the file " << in_file_name << endl; in_stream >> firstn >> secondn >> thirdn; sum = firstn + secondn + thirdn; /* The following set of lines will write to the screen */ cout << "The sum of the first 3 numbers from " << in_file_name << " is " << sum << endl; cout << "Placing the sum into the file " << out_file_name << endl; /* The following set of lines will write to the output file */ out_stream << "The sum of the first 3 numbers from " << in_file_name << " is " << sum << endl; in_stream.close( ); out_stream.close( ); cout << "End of Program." << endl; return 0; }