1

このウェブサイトでの私の 4 回目。ここに来るのは、実際に質問に答えてもらっているからです。異なるファイル (テキスト ファイル) を結合するタスクがあります。それらのファイルには名前/グレードが含まれており、12個ほどあります。基本的に、それらすべてを「名前」「グレード1」「グレード2」などの1つのファイルに結合する必要があります...いくつかを結合することはできましたが、どの単語が再び使用されているかを見つける方法に頭を悩ませることはできません(同じ名前が 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 関数を取得しました。今まで知らなかった。

4

1 に答える 1

0

名前だけの 2 つのファイルがあると仮定した例を示します。具体的には、入力ファイルの構造を確認する必要があります。

#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番目のファイル2:

Paul
Mary
Simon

上記のコードは次のように出力John Mary Nick Paul Simon されます。Paul

于 2013-05-27T09:56:56.300 に答える