在c++中组合不同的文本文件
Combining different text files in C++
这是我第四次来这个网站了。我来这里只是因为我的问题得到了答案。我的任务是将不同的文件(文本文件)组合在一起。这些文件包括名字和成绩,我有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
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入