Start New Discussion within our Software Development Community

Read line by line from data2.txt, compare with data1.txt lines, if match , remove , else append to a new file (result.txt) .
mathces are exact string matches, both are text files.
And i also need to make the directory of the file to be user input, so this program must be able to compare 2 files which user inputs and generate a report.

My code as follows.

-------------------
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream ifs1("data1.txt");
ifstream ifs2("data2.txt");
ofstream ofs("result.txt");
string line1;
string line2;
while (!ifs2.eof())
{
getline(ifs2,line2);
while (!ifs1.eof()) {
getline(ifs1,line1);
if (line1!=line2) {
ofs << line1;
ofs << "\n";
}
else {
}
}
}
return 0;
}
-------------------------

data1.txt :
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5

data2.txt
This is line 5
This is line 1

Result.txt should be:
---------------------
This is line 2
This is line 3
This is line 4

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
	ifstream ifs1("data1.txt");
	vector<string> data1;
	if (ifs1.is_open()){
		string line;
		while(getline(ifs1, line)){
			data1.push_back(line);
		}
	}
	else{
		cout << "Unable to open file data1.txt";
		return 1;
	}
	ifstream ifs2("data2.txt");
	if (ifs2.is_open()){
		string line;
		while(getline(ifs2, line)){
			for(size_t i = 0; i < data1.size(); ++i){
				if (line == data1[i])
					data1.erase(data1.begin()+i);
			}
		}
	}
	else{
		cout << "Unable to open file data2.txt";
		return 1;
	}
	ofstream ofs("result.txt");
	if (ofs.is_open()){
		for(size_t i = 0; i < data1.size(); ++i){
			ofs << data1[i] << endl;
		}
	}
	else{
		cout << "Unable to open file result.txt";
		return 1;
	}
	return 0;
}
This question has already been answered. Start a new discussion instead.