读入两个文本文件,然后将它们组合在一起

reading in two text files and then combining them

本文关键字:然后 在一起 组合 文件 文本 两个      更新时间:2023-10-16

我在编译我编写的代码时遇到了问题。这段代码旨在读取两个文本文件,然后输出这两个文件中的行。然后,我希望能够放置两个文件并将它们组合在一起,但第一行是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(...))

如果你想阅读和打印交替的行,有两种可能的方法:

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

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

对于第二种选择,你可以这样做:

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);

或者简单地说:

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

您的第二个if语句在main()-函数之外。在第一次返回0之后;关闭main()函数。代码中的另一个问题是,如果第二个if语句在main()-函数中,那么它永远不会到达,因为返回0;结束main()。我想,如果第一个文件流是"坏的",您只想执行return,所以您需要一个其他文件流的作用域;

相关文章: