【问题标题】:Copy line by line in C++ [duplicate]在C ++中逐行复制[重复]
【发布时间】:2015-10-30 03:39:22
【问题描述】:

我正在尝试将 2 个文件复制到 1 个文件中,例如 标识 1 。名称 1 。 身份证2。名称2。 但我做不到...我应该如何从每个文件中复制每一行。

#include <iostream>
#include <fstream>
using namespace std;
int main()
{

 ifstream file1("ID.txt");
   ifstream file2("fullname.txt");
   ofstream file4("test.txt");
   string x,y;
  while (file1 >> x )
   {
       file4 <<  x <<" . ";
       while (file2 >> y)
       {
           file4 << y <<" . "<< endl;
       }
   } 


}

【问题讨论】:

  • 也许可以看看std::getline
  • 或者您可以使用已经完成此操作的工具。 paste ID.txt fullname.txt &gt; test.txt

标签: c++ file copy


【解决方案1】:

首先,逐行阅读。

ifstream file1("ID.txt");
string line;
ifstream file2("fulName.txt");
string line2;


while(getline(file1, line))
{
    if(getline(file2, line2))
    {
        //here combine your lines and write to new file
    }
}

【讨论】:

  • 这里的问题是,如果 file2 比 file1 长,它会有效地将输出文件截断为 file1 的大小。
  • 他可以根据需要修改代码,我不会为他编写代码。在我看来,他正在使用这两个文件构建价值对,如果一个比另一个短,他必须决定是停止还是继续,我认为他停止但不知道他的要求
【解决方案2】:

我只是将每个文件分别处理到它们自己的列表中。之后将列表的内容放入组合文件中。

ifstream file1("ID.txt");
ifstream file2("fullname.txt");
ofstream file4("test.txt");
std::list<string> x;
std::list<string> y;
string temp;

while(getline(file1, temp))
{
    x.add(temp);
}

while(getline(file2, temp))
{
    y.add(temp);
}

//Here I'm assuming files are the same size but you may have to do this some other way if that isn't the case
for (int i = 0; i < x.size; i++)
{
    file4 << x[i] << " . ";
    file4 << y[i] << " . ";
}

【讨论】:

  • std::list 没有 [] 运算符。你可能在想 std::vector。也就是说,使用 std::list 和迭代器可能有一些性能优势。也没有考虑到 y.size() 的情况
  • 我不知道文件有多大,但是在处理它们之前将这两个文件读入内存似乎效率不高,并且可能导致内存不足问题。
猜你喜欢
  • 2021-05-09
  • 1970-01-01
  • 2023-03-27
  • 2015-05-19
  • 2020-02-21
  • 2011-07-19
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
相关资源
最近更新 更多