C++读取txt文件并在每一行追加数据

C++ Read txt file and append data in each line

我想打开一个文件,在每一行的末尾追加一个字符串。

我有这个代码:

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

//argv[1] input file 
//argv[2] string to add in the end of each line
//argv[3] output file
int main(int argc, char *argv[]){

  ifstream open_file(argv[1]);
  if (!open_file) {
      std::cerr << "Could not open input file\n";
      return 0;
  } 
  ofstream new_file(argv[3]);
  if (!new_file) {
     std::cerr << "Could not create output file\n";
     return 0;
  } 
  string s = argv[2];
  string str;
  while (getline(open_file, str)) {
     new_file << str << s << "\n";
  }
}

问题是字符串没有添加到每一行的末尾。它正在为每个试图附加的字符串创建一个新行。

所以我运行例如:./appendstring.e wordlist.txt hello new_wordlist.txt

这是输出:

我真的不知道我做错了什么。

提前致谢。

也许您的第一个文件包含 \r\n 行尾序列..

您可能必须删除第一个文件中已有的 \r 字符,因为您正在读取结尾带有 \r 的字符串。

Trim 关闭 \r 结束 str,在你使用这行代码之前:

new_file << str << s << "\n";

看这里 http://www.cplusplus.com/reference/string/string/getline/