Ye it's fairly simple to write to an output file.
So you already have the <fstream> header.
<fstream> – header file that must be included in a program that requires file I/O
In there you have two data types.
ifstream – data type for variables that represent input files
ofstream– data type for variables that represent output files
So just like how you assigned "fin" to ifstream.
You can create a variable called "fout" to ofstream.
Like so:
ofstream fout;
If you already know the data file you want to write in, you would use the same snytax such as:
1 2 3
|
fout.open("output file.txt")
fout << "I can write here" << endl;
fout.close();
|
If you want to prompt the user for the input or output file, then you would create a string variable that represents the name of the file.
Here's an example for prompting a user for an input file.
1 2 3 4 5 6 7 8 9 10 11
|
ifstream infile; //infile represents the input file
string fname; //actual name of file
//prompt for name of input file to be opened
cout << "Please enter name of input file" << endl;
cin >> fname;
//read name of file to open
//open input file for reading
infile.open(fname.c_str());
/* c_str() is a function that converts a string variable into a null-
terminated array of characters, which is
the type of parameter the open function expects */
|
For your particular program do this:
create the output file by using ofstream
create a string variable for the name of the file
prompt the user for the output file
read in the name of the file into your string variable
open the file
write to the file
close the file.