I wish to input (read) the contents of the file called "numbers.dat" (that appears at the bottom of this writeup) into the file (sum.dat) following immediately here below; with the view of manipulating these contents and outputting the results within this file called "sum.dat". However, all my previous attempts have ended with: "Input file opening failed"!
I am using Code::Blocks 10.05 running on Windows.
I am unable to figure out why the input file fails to open. What is wrong here?
//Following is the file numbers.datCode:#include <fstream> #include <iostream> #include <cstdlib> int main() { using namespace std; char in_file_name[16], out_file_name[16]; ifstream in_stream; ofstream out_stream; cout << "Enter the input file name (maximum of 15 characters):\n"; cin >> in_file_name; cout << "Enter the output file name (maximum of 15 characters):\n"; cin >> out_file_name; cout << "I will read numbers from the file " << in_file_name << " and\n" << "place the sum in the file " << out_file_name << endl; in_stream.open(in_file_name); if (in_stream.fail ()) { cout << "Input file opening failed.\n"; exit(1); out_stream.open(out_file_name); if (out_stream.fail ()) { cout << "Output file opening failed.\n"; exit(1); } int first, second, third; in_stream >> first >> second >> third; out_stream << "The Sum of the first 3\n" << "numbers in " << in_file_name << endl << " is " << (first + second + third) << endl; in_stream.close(); out_stream.close(); cout << " End of Program.\n"; } return 0; }
Code:#include <fstream> #include <string> #include <iostream> #include <cstdlib> using namespace std; int main() { int num1, num2, num3, num4; string numbers; cout << "Enter the four numbers: " << endl; cin >> num1 >> num2 >> num3 >> num4; cout << "The numbers are: " << num1 << " "<< num2 << " " << num3 << " " << num4; ofstream writer("numbers.dat"); if(!writer) { cout << "Error opening file for output" << endl; return -1; } writer << numbers << endl; writer.close(); return 0; }



1Likes
LinkBack URL
About LinkBacks



CornedBee