C++ 在运行之间清除文本文件的内容导致只写入最后一行

C++ Clearing content of text file between runs causes only last line to be written

我正在尝试将几行内容写入文本文件。我想在每个 运行 上追加之前清空文件。我能够清除以前的内容,但是当我这样做时,出于某种原因只有输入文件的最后一行附加到输出文件。我还尝试使用 remove() 删除文件并收到相同的输出。

另一方面,在不清除文件或删除文件的情况下,所有内容都会正确附加到输出文件中。

我很乐意找到解决这个问题的方法,也许能理解为什么会这样。我正在使用 C++11。

我看过这里:How to clear a file in append mode in C++

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stdio.h>

int main() {
  std::fstream infile;
  std::string line;

  infile.open("file.txt" , std::ios::in);

  while (std::getline(infile, line)) {
    std::istringstream line_buffer(line);
    std::string word;

    std::fstream outfile;
    outfile.open("out.txt", std::ios::out);
    outfile.close();
    outfile.open("out.txt", std::ios::app);
    while (line_buffer >> word) {
      std::cout << word << " ";
      outfile << word << " ";
    }
    std::cout << std::endl;
    outfile << std::endl;
  }
  return 0;
}

问题是您在 while 循环的每次迭代中清除文件,您可以像这样在循环之前打开输出文件:

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stdio.h>

int main() {
  std::fstream infile;
  std::string line;

  infile.open("file.txt" , std::ios::in);

  std::fstream outfile;
  outfile.open("out.txt", std::ios::out);

  while (std::getline(infile, line)) {
    std::istringstream line_buffer(line);
    std::string word;

    while (line_buffer >> word) {
      std::cout << word << " ";
      outfile << word << " ";
    }
    std::cout << std::endl;
    outfile << std::endl;
  }

  outfile.close();
  return 0;
}