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

标签 c++ text-files

我第四次访问这个网站。只是来这里是因为我的问题实际上得到了回答。我的任务是将不同的文件(文本文件)组合在一起。这些文件包括姓名/成绩,我有 12 个。基本上我需要将它们全部合并到一个文件中,其中包含“名称”“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

和你的第二个文件2:

Paul
Mary
Simon

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

关于c++ - 在 C++ 中组合不同的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16767876/

相关文章:

Java从带有撇号和连字符的文件中读取单词并将它们计为2个单词

c# - 如何创建 .txt 文件并将其写入 c# asp.net

java - 如何使用java替换文本文件中的字符串?

c++ - 在C++中分配为true或false的随机对象

c++ - cpp 检查字符串是否是有效域名?

c++ - 标准在哪里定义 volatile 变量可以更改?

C++ SDL2,如何定期更新渲染文本? (ttf)

excel - VBA二进制文件-cnc程序

debugging - 使用 VBA 将文本文件复制到 Excel 时出现问题

c++ - 将图像添加到 Pong 游戏