0

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

3 回答 3

1

首先,不要做while (file.good())or 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);
于 2013-08-16T11:07:57.140 回答
0

或者简单地说:

cout << ifstream(filename1, ios::in | ios::binary).rdbuf();
cout << ifstream(filename2, ios::in | ios::binary).rdbuf();
于 2013-08-16T11:15:13.240 回答
0

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

于 2013-08-16T11:16:45.367 回答