File Names as Input
In file I/O, sometimes we want to input the name of a file from the keyboard. This can be done using a string (object).
-
A string is an object containing a sequence of characters.
-
We need to declare a variable to hold a string. This can be done by the declaration:
string filename;
which can hold a string containing any number of characters.
-
Strings will be dealt with in greater depth in ch. 8.
-
There is one complication when a string is used to store the name of a file which will be attached to a file for input or output.
This is due to the fact that the argument of the member function open must be a cstring and not a string object.
-
Fortunately a string object has a member function c_str( ) which can be used to convert the string object into a cstring.
-
An example is shown as follows:
//Read three numbers from the file specified by the user, add up the
//numbers, and write the sum to another file specified by the user.
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main( )
{
int first, second, third;
// declare 2 character arrays for the input and output file names
string in_file_name, out_file_name;
ifstream in_stream;
ofstream out_stream;
cout << "I will sum three numbers taken from an input\n"
<< "file and write the sum to an output file.\n";
cout << "Enter the input file name (with no spaces):\n";
cin >> in_file_name;
cout << "Enter the output file name (with no spaces):\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.c_str( ));
if (in_stream.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
out_stream.open(out_file_name.c_str( ));
if (out_stream.fail( ))
{
cout << "Output file opening failed.\n";
in_stream.close( );
// otherwise you exit the program without closing
// the input file!
exit(1);
}
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;
} //end main