In: Computer Science
In c++ please.
Write a program that reads the contents of two text files and compares them in the following ways:
It should display a list of all the unique words contained in both files.
It should display a list of the words that appears in both files.
It should display a list of the words that appears in the first file, but not the second.
It should display a list of the words that appears in the second file, but not the first.
It should display a list of the words that appears in either the first or second file, but not both.
C++ Code:
#include <bits/stdc++.h>
using namespace std;
//map for two files.
map<string,int>set1;
map<string,int>set2;
// driver code
int main()
{
// filestream variable file
fstream file1,file2;
string word, t, q, filename,filename2;
// filename of the file
filename = "paragraph.txt";
filename2= "paragraph2.txt";
// opening file
file1.open(filename.c_str());
file2.open(filename2.c_str());
// extracting words from the file
while (file1 >> word)
set1.insert({word,1});
}
cout<<"Unique Word of text file 1:\n\n";
while (file2 >> word)
{
set2.insert({word,1});
}
//print unique word of file1.
for(auto i=set1.begin();i!=set1.end();i++)
{
cout<<i->first<<"
";
//print the words.
}
cout<<"\n\n\nUnique Word of text file 2:\n\n";
//print unique word of file2.
for(auto i=set2.begin();i!=set2.end();i++)
{
cout<<i->first<<"
";
//print the words.
}
cout<<"\n\n\n Words that appears in both
files:\n\n";
for(auto i=set1.begin();i!=set1.end();i++)
{
if(set2[i->first]==1)
cout<<i->first<<" ";
}
cout<<"\n\n\n words that appears in the first file, but
not the second:\n\n";
for(auto i=set1.begin();i!=set1.end();i++)
{
if(set2[i->first]==0)
cout<<i->first<<" ";
}
cout<<"\n\n\n words that appears in the second file, but
not the first:\n\n";
for(auto i=set2.begin();i!=set2.end();i++)
{
if(set1[i->first]==0)
cout<<i->first<<" ";
}
cout<<"\n\n\n words that appears in either the first or
second file, but not both:\n\n";
for(auto i=set1.begin();i!=set1.end();i++)
{
if(set2[i->first]==0)
cout<<i->first<<" ";
}
for(auto i=set2.begin();i!=set2.end();i++)
{
if(set1[i->first]==0)
cout<<i->first<<" ";
}
return 0;
}
Output: