At the moment, the copyints program always uses numbers.dat for its input
file, and always uses output.dat for it’s output file. We will change
that. To make the change, find these lines in the main program:
// Names for the text files.
char in_file[40] = "numbers.dat";
char out_file[40] = "output.dat";
The data type char, and the number [40] indicates that each of these
variables is capable of holding a sequence of up to 40 characters.
You’ll read about these sequence of characters later in the semester;
for now it is sufficient to know that you can use such a sequence to hold
the name of a file such as "numbers.dat" or "output.dat". So,
in our program we declare the variables in_file and out_file, and immediately
assign the names of the input and output files (numbers.dat and output.dat).
As an improvement, we will let the program’s user type the name of the input
and output files. To carry out the improvement, start by getting rid of the
assignments in the four lines that you have just seen. Change the lines to
this:
// Names for the external files,
// to be read from the user of the program.
char in_file[40];
char out_file[40];
Now we have the variables in_file and out_file, but these variables have not
been assigned a value. We need to add lines that will read the names of the
files from the program’s user. This can be carried out just before each file
is opened. For example, the name of the input file is used to open the actual
input file in the statment: ins.open(in_file); Just before this open statement
we can read the name of the input file, as shown here:
// Open input and output files, exit on any error
cout << "Please type the input file name: ";
cin >> in_file;
ins.open(in_file);
After these statements, the input file stream (named ins) will be attached to
whatever file was requested by the program’s user. For example, if the user
types numbers.dat, then the program will read input from numbers.dat. If the
user types message.dat, then the program will take input from message.dat.
We can use the same appraoch to ask the user for the name of the output file.
Find the place in the main program where the output file is opened, and add
statements to read the name of the output file from the program’s user. Do
this now, and then run your program again. When you are prompted for an input
file you may type numbers.dat, or type message.dat--the choice is yours.
You may type whatever name you like for the output file (though I suggest
that the file ends with .dat to indicate that it is a data file rather than a
cxx file).