Checking for duplicate numbers in two files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
int dothis()
{
	
ifstream afile ("a.txt");
ifstream gfile ("b.txt");
	
if (afile.is_open())
{
	if (gfile.is_open())
	{
		std::string part1;
		std::string part2;
		std::string part3;
		std::string part4;
		int character;
		while((character = gfile.get()) != EOF) //while we haven't reach the end of the file
		{
			part1 += char(character); //add the character to the string
		}
		
		vector<int> List;
		vector<int>::iterator It;
		
		int Number;
		
		while(!afile.eof())
		{
			afile >> Number;
			List.push_back(Number);   // Reads each number and inserts it into list 
		}
						
		gfile.close();
		afile.close();
		cout << "files closed" << endl;
		for (vector<int>::iterator i = List.begin() ; i < List.end() ; i++)
			for (vector<int>::iterator j = i+1 ; j < List.end(); j++)
				if (*i == *j) 
					List.erase(j--);
		
		cout << "half way through do this" << endl;
		ofstream File2;
		File2.open("c.txt", ios::app); 
			
		for(vector<int>::iterator i = List.begin(); i != List.end(); i++)
		{	
			if (part1.find(*i)!=string::npos)
			{
				z = 1;
			}
			else
			{
				File2 << *i;
				File2 << "\n";
			}
		}
		cout << "finish do this" << endl;
	}
     }
cout << "finished do this" << endl;
return 0;
}


I'm trying to compare the numbers found in files a.txt and b.txt. After comparing them I only want to send the numbers that are NOT found in both files to file c.txt. I convert one file into a string and the 2nd file into a vector. Then I look for the numbers from the vector within the string. If it doesn't find it, from what I understand, the "else if" is supposed to occur ONLY if the number is NOT found in the string. I thought the current setup should do it but its not working, I'm still finding numbers in file C that are found in both files. BTW, the "z = 1" I just put there to fill in the if statement.
Last edited on
The operation you're doing is known as symmetric set difference. C++ has a function for that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <fstream>
#include <iterator>
#include <set>
#include <algorithm>
void dothis()
{
   std::ifstream afile ("a.txt");
   std::istream_iterator<int> abeg(afile), aend;
   std::set<int> aset(abeg, aend);

   std::ifstream gfile ("b.txt");
   std::istream_iterator<int> gbeg(gfile), gend;
   std::set<int> gset(gbeg, gend);

   std::ofstream cfile("c.txt");
   set_symmetric_difference(aset.begin(), aset.end(),
                            gset.begin(), gset.end(),
                            std::ostream_iterator<int>(cfile, "\n"));
}

demo: http://ideone.com/YFnQ6
Last edited on
Thank you very much, thus far it works great and is providing the results I need.
Topic archived. No new replies allowed.