Reputation:
My fourth time on this website. Only come here because I actually have my questions answered. I have a task to combine different files (text files) together. Those files include names/grades, and I have like 12 of them. Basically I need to combine all of them into one file with "Name" "Grade1" "Grade2" etc... I have managed to combine a couple but I just can't wrap my head around how to find which words are used again (same names repeated several times since they appear in all 12 files) and I would appreciate if someone can point me in the right direction. Thanks! By the way, this is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("example.txt");
std::ifstream file1( "Nfiles/f1.txt" ) ;
std::ifstream file2( "Nfiles/f2.txt" ) ;
std::ifstream file3( "Nfiles/f3.txt" ) ;
std::ofstream combined_file( "combined_file.txt" ) ;
combined_file << file1.rdbuf() << file2.rdbuf() << file3.rdbuf() ;
myfile.close();
return 0;
}
PS: Got the fstream functions from a quick search. Never knew about them till' now.
Upvotes: 1
Views: 2348
Reputation: 8920
I will give you an example assuming that you have two files with only the names, for something more specific you have to saw us the structure of the input files.
#include <vector>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iterator>
int main(int argv,char** argc)
{
if(argv<3)
{
std::cout << "Wrong input parameters" << std::endl;
return -1;
}
//read two files
std::fstream input1;
std::fstream input2;
input1.open(argc[1]);
input2.open(argc[2]);
if((!input1)||(!input2))
{
std::cout << "Cannot open one of the files" << std::endl;
}
std::istream_iterator<std::string> in1(input1);
std::istream_iterator<std::string> in2(input2);
std::istream_iterator<std::string> eof1;
std::istream_iterator<std::string> eof2;
std::vector<std::string> vector1(in1,eof1);
std::vector<std::string> vector2(in2,eof2);
std::vector<std::string> names;
std::copy(vector1.begin(),vector1.end(),back_inserter(names));
std::copy(vector2.begin(),vector2.end(),back_inserter(names));
//std::copy(names.begin(),names.end(),std::ostream_iterator<std::string>(std::cout," "));
std::sort(names.begin(),names.end());
auto it=std::unique(names.begin(),names.end());
names.erase(it);
std::copy(names.begin(),names.end(),std::ostream_iterator<std::string>(std::cout," "));
};
Assuming that your file1 :
Paul
John
Nick
and your second file2:
Paul
Mary
Simon
The above code will print: John Mary Nick Paul Simon
It will not print Paul
twice
Upvotes: 0