954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read line by line from 2 text files and compare both and generate a report!!

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

all blacks
Newbie Poster
9 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 
#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;
}
ivailosp
Junior Poster
129 posts since Apr 2008
Reputation Points: 21
Solved Threads: 22
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You