basically i have 4 files 2 contain the following data . Trying to find out data which is common and not common in both files and write it out to files common and not common. It almost works except for it doesn't compare the last item in the list before it ends. :(
Thanks.
Final1.txt
3
6
9
12
15
18
21
Final2.txt
9
12
15
18
21
24
27
30
33
36
--stores numbers which are common
Common
9
12
15
18
doesn't get this number: 21
Not common
3
6
24
27
30
33
36
#include <iostream>
#include <fstream>
using namespace std;
//open file to read from
void intializeList(ifstream& List, char* input);
//open file to write to
void intializeoutput(ofstream& List, char* output);
//getitem from file
int getNextitem(ifstream& file);
//output item to correct file
void setnextitem(ofstream& file, int number);
int main()
{
int moreItems;
ifstream Final1,Final2;
ofstream Common,Notcommon;
//open input and output files
intializeList(Final1,"Final1.txt");
intializeList(Final2,"Final2.txt");
intializeoutput(Common,"Common.txt");
intializeoutput(Notcommon,"Notincommon.txt");
//get first item in both lists
int list1=getNextitem(Final1);
int list2=getNextitem(Final2);
moreItems=list1&&list2;
//loop until no items in one list
while(moreItems)
{
//item from list 1 smaller than item from list 2
if(list1<list2)
{
cout<<"list1<list2\n";
//write out to not common file
setnextitem(Notcommon,list1);
//get next value in list1
list1=getNextitem(Final1);
}
//items are equal
else if(list1=list2)
{
cout<<"list1=list2\n";
setnextitem(Common,list1);
list1=getNextitem(Final1);
list2=getNextitem(Final2);
}
else
{
cout<<"list1>list2\n";
//write out to not common file
setnextitem(Notcommon,list2);
//get next value in list2
list2=getNextitem(Final2);
}
if(Final1.eof()||Final2.eof())
{
break;
}
}
//read in last item from the list which and then
//copy all the remaining data from the list which isn't empty to not in common
while(!Final1.eof())
{
list1=getNextitem(Final1);
setnextitem(Notcommon,list1);
}
while(!Final2.eof())
{
list2=getNextitem(Final2);
setnextitem(Notcommon,list2);
}
Final1.close();
Final2.close();
Common.close();
Notcommon.close();
return 0;
}
void intializeList(ifstream& List, char* input)
{
List.open(input);
if(List.fail())
{
cout<<"error opening file"<<input<<"\n";
}
else
{
cout<<"file input named "<<input<<" opened\n";
}
}
void intializeoutput(ofstream& List, char* output)
{
List.open(output);
if(List.fail())
{
cout<<"error opening file"<<output<<"\n";
}
else
{
cout<<"file output named "<<output<<" opened\n";
}
}
int getNextitem(ifstream& file)
{
int data;
//reached end of file
if(file.eof())
{
cout<<"end of file reached\n";
file.close();
}
else
{
file>>data;
return data;
}
}
void setnextitem(ofstream& file, int number)
{
cout<<number<<endl;
file<<number<<"\n";
}