【问题标题】:C++ Read txt file and append data in each lineC++读取txt文件并在每一行追加数据
【发布时间】:2017-11-04 19:00:52
【问题描述】:

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

我有这个代码:

#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

这是输出:

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

提前致谢。

【问题讨论】:

  • 只是一个提示:读取文件并将push_back() 的每一行添加到std::vector&lt;std::string&gt;,然后将所需的文本附加到每一行。最后,将所有行写回文件。

标签: c++ iostream ifstream ofstream


【解决方案1】:

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

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

在使用这行代码之前,将\rstr 的末尾剪掉:

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

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

【讨论】:

  • 已修复!非常感谢。你是对的。我所做的只是添加: str.erase(str.size() - 1);
  • 很高兴它有帮助。欢迎来到 Stackoverflow :)
猜你喜欢
  • 1970-01-01
  • 2023-04-09
  • 2021-10-18
  • 2021-02-06
  • 2013-02-16
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
相关资源
最近更新 更多