Write a program (in C++) that opens two text files (input1.txt and input2.txt) f
ID: 3914488 • Letter: W
Question
Write a program (in C++) that opens two text files (input1.txt and input2.txt) for input and one for output (output.txt). The program should merge the two input files in the output files. While doing the merge, it will read one line from input1.txt and one line from input2.txt and write those in the output file one after other. Then it will read the next line from input1.txt and next line from input2.txt and write them one after other in the output file. Here is an example. input1.txt: This is the first line in input1.txt. This is the second line in input1.txt. This is the third line in input1.txt. This is the fourth line in input1.txt. input2.txt: This is the first line in input2.txt. This is the second line in input2.txt. This is the third line in input2.txt. outtput.txt This is the first line in input1.txt. This is the first line in input2.txt. This is the second line in input1.txt. This is the second line in input2.txt. This is the third line in input1.txt. This is the third line in input2.txt. This is the fourth line in input1.txt. After the writing in output.txt, count the number of lines in output.txt. Also, write the number of times term ‘input1’ appears in output.txt file.
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int findFrequency(string s1, string s2) {
int count = 0, i, j = 0, k;
k = s2.length();
for (i = 0; i < s1.length();)
{
if (s1[i] == ' ')
{
i++;
}
else
{
if (s1[i] == s2[j])
{
j++;
i++;
}
else if (j == k)
{
j = 0;
count++;
i--;
}
else
{
i++;
j = 0;
}
}
}
return count;
}
int main () {
string line1, line2;
int count = 0;
string find = "input";
//using ifstream to input file stream from a text file
ifstream myfile1 ("input1.txt");
ifstream myfile2 ("input2.txt");
ofstream outfile ("output.txt");
if (myfile1.is_open() && myfile2.is_open() && outfile.is_open())
{
while (!myfile1.eof() && !myfile2.eof())
{
getline (myfile1, line1);
getline(myfile2, line2);
count += findFrequency(line1, find);
count += findFrequency(line2, find);
outfile << line1 << endl;
outfile << line2 << endl;
}
getline (myfile1, line1);
getline (myfile2, line2);
if(!line1.empty()) {
count += findFrequency(line1, find);
outfile << line1 << endl;
}
if(!line2.empty()) {
count += findFrequency(line2, find);
outfile << line2 << endl;
}
while (!myfile1.eof())
{
getline (myfile1, line1);
count += findFrequency(line1, find);
outfile << line1 << endl;
}
while (!myfile2.eof())
{
getline(myfile2, line2);
count += findFrequency(line2, find);
outfile << line2 << endl;
}
outfile << "Number of occurences of word 'input' = " << count << endl;
myfile1.close();
myfile2.close();
outfile.close();
}
else
cout << "Can't open the mentioned files!!!";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.