C++ 读入两个文本文件,然后合并它们

C++ 读入两个文本文件,然后合并它们,c++,io,text-files,C++,Io,Text Files,我在编译我写的代码时遇到了问题。此代码用于读取两个文本文件,然后输出这两个文件中的行。然后,我希望能够把这两个文件,并结合他们,但与file1文本在第一行和file2文本是在第二行 这是我的密码: #include <iostream> #include <fstream> #include <cmath> #include <string> using namespace std; int main() { std::ifstream f

我在编译我写的代码时遇到了问题。此代码用于读取两个文本文件,然后输出这两个文件中的行。然后,我希望能够把这两个文件,并结合他们,但与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;}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
std::ifstream file1(“file1.txt”);
std::ifstream file2(“file2.txt”);
//std::of Stream combinedfile(“combinedfile.txt”);
//组合文件名;
file2.open(文件名);
if(file1.is_open())
{
while(file1.good())
{
getline(文件名,行);

首先,当(file.good())
或(!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);
    
    std::ifstream file1(“file1.txt”);
    std::ifstream file2(“file2.txt”);
    如果(!file1 | |!file2)
    {
    标准::cout或简单地:

    cout << ifstream(filename1, ios::in | ios::binary).rdbuf();
    cout << ifstream(filename2, ios::in | ios::binary).rdbuf();
    

    cout第二条if语句在main()-函数之外。在第一次返回0后,关闭main()-函数。
    代码中的另一个问题是,如果第二条if语句位于main()-函数内,则永远不会到达它,因为返回0;将结束main()。
    
    如果第一个文件流是“坏”的,我猜您只想执行return,所以您需要为else指定一个作用域;

    编译器怎么说?