在c++中组合不同的文本文件

Combining different text files in C++

本文关键字:文本 文件 c++ 组合      更新时间:2023-10-16

这是我第四次来这个网站了。我来这里只是因为我的问题得到了答案。我的任务是将不同的文件(文本文件)组合在一起。这些文件包括名字和成绩,我有12个。基本上,我需要把它们合并到一个文件中,文件中有"Name"、"Grade1"、"Grade2"等等。我已经设法结合了一对,但我只是不能围绕如何找到哪些词再次使用(相同的名字重复了几次,因为它们出现在所有12个文件)和如果有人能给我指个方向,我会很感激的。谢谢!顺便说一下,这是我的代码:

#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:从快速搜索中获得了fstream函数。直到现在才知道。

我将给你一个例子,假设你有两个只有名字的文件,对于更具体的东西,你必须看到我们输入文件的结构。

#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," "));
};

假设你的file1:

Paul
John
Nick

和你的第二个文件e2:

Paul
Mary
Simon

上面的代码将打印:John Mary Nick Paul Simon它不会打印两次Paul