Write a C++ program that opens two text files for input and one for output. The
ID: 3758349 • Letter: W
Question
Write a C++ program that opens two text files for input and one for output. The program should concatenate the corresponding lines of the input files, use a space as a separator, and write the results to the output file. If one file is shorter than the other, the remaining lines in the longer file should also be copied to the output file. For example, suppose the first input file has these contents:
eggs kites donuts
balloons hammers
stones
And suppose the second input file has these contents:
zero lassitude
finance drama
The resulting file would have these contents:
eggs kites donuts zero lassitude
balloons hammers finance drama
stones
Explanation / Answer
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const char *fileA="bat1.dat";
const char *fileB="bat2.dat";
const char *fileC="bat3.dat";
char ch;
int main (void)
{
ifstream fin;
ofstream fout;
fin.open(fileA);
if (!fin.is_open())
{
cerr << "Can't open the file " << fileA << " ";
exit(1);
}
if (fin.is_open())
{
fout.open(fileC);
while(fin.get(ch))
fout << ch;
fout.close();
}
fin.close();
(fileC, ios_base:ut|ios_base::app);
fout.close();
fin.open(fileB);
if (!fin.is_open())
{
cerr << "Can't open the file " << fileB << " ;
exit(1);
}
if (fin.is_open())
{
fout.open(fileC);
while(fin.get(ch))
fout << ch;
fout.close();
}
fin.close();
(fileC, ios_base:ut|ios_base::app);
fout.close();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.