我在编写此代码时遇到了问题。此代码用于读取两个文本文件,然后在这两个文件中输出该行。然后,我希望能够放置两个文件并将它们组合在一起,但是在第一行上出现file1文本,而在第二行之后出现file2文本。

这是我的代码:

#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
using namespace std;


int main()

{

std::ifstream file1("file1.txt");
std::ifstream file2("file2.txt");
//std::ofstream combinedfile("combinedfile.txt");
//combinedfile << file1.rdbuf() << file2.rdbuf();


char filename[400];
string line;
string line2;

cout << "Enter name of file 1(including .txt): ";
cin >> filename;

file1.open(filename);
cout << "Enter name of file 2 (including .txt): ";
cin >> filename;

file2.open(filename);

  if (file1.is_open())
  {
    while (file1.good() )
    {
      getline (filename,line);
      cout << line << endl;

    }
   file1.close();
  }

  else cout << "Unable to open file";

 return 0;
}
 if (file2.is_open())
  {
    while (file2.good() )
    {
      getline (filename,line);
      cout << line << endl;
    }
   file2.close();
  }

  else cout << "Unable to open file";

  return 0;}

最佳答案

首先,不要执行while (file.good())while (!file.eof()),它将无法按预期工作。而是像while (std::getline(...))

如果要读取和打印备用行,可以采用两种方法:


将两个文件都读入两个std::vector对象,然后将这些矢量打印出来。或者可能将两个向量合并为一个向量,然后打印出来。
从第一个文件读取一行并进行打印,然后从第二个文件读取并进行循环打印。


第一种选择可能是最简单的,但使用的内存最多。

对于第二种选择,您可以执行以下操作:

std::ifstream file1("file1.txt");
std::ifstream file2("file2.txt");

if (!file1 || !file2)
{
    std::cout << "Error opening file " << (file1 ? 2 : 1) << ": " << strerror(errno) << '\n';
    return 1;
}

do
{
    std::string line;

    if (std::getline(file1, line))
        std::cout << line;

    if (std::getline(file2, line))
        std::cout << line;

} while (file1 || file2);

10-08 12:00