Monday 5 August 2013

Union of data contained in 2 files

if set1.txt file contains 2 3 56 4 5 7 and set2.txt contains 8 5 4 9 7 85
Union.txt file would contain  2 3 56 4 5 7 8 9 85



#include<iostream>
#include<fstream>
#include<cmath>
#include<cstdlib>
using namespace std;
class Unionofelements
{public:
    string  element;
    void  read2files(ifstream &input1 ,ifstream &input2, string store[] ,int &storecount );
    void copyunion2file(string  store[],int &storecount, ofstream &output);  //set has no repition of elements

};

int main()
{Unionofelements group;
string  store[100]; int storecount=0;
    ifstream f1("set1.txt"),f2("set2.txt");
    ofstream f3("Union.txt");
    if(f3.fail())
    {
        cout<"The file to be written not accessed";
        exit(1);
    }
    group.read2files(f1,f2,store,storecount);
    group.copyunion2file(store,storecount,f3);
    return 0;

}

 void Unionofelements::read2files(ifstream &input1 ,ifstream &input2, string store[] ,int &storecount )
    { int i;
    for(i=0;!input1.eof();i++)
        {input1>>element;
        store[i]=element;
        }
        i--;  //note this
        for(;!input2.eof();i++)
        {input2>>element;
        store[i]=element;
        }
        i--;
        storecount=i;
        for(int k=0;k<i;k++)  //displaying elements from both sets
            cout<<store[k]<<" ";
        cout<<"\nnumber of elements :  "<<i<<endl;
    }

    void Unionofelements::copyunion2file(string  store[],int &storecount, ofstream &output)  //set has no repition of elements
    {int i,j,remember;
       for(i=0;i<storecount;i++)
       {   for(j=i+1;j<storecount;j++)
            {if (store[i]==store[j])
               {remember=j;storecount--;
                  for(;remember<storecount;remember++)
                    store[remember]=store[remember+1];
                  j--;
                }

             }
          cout<<store[i] <<"  ";
          output<<store[i]<<" ";
       }

cout<<"\nUnion of elements copied.....";

    }

No comments:

Post a Comment