Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;读取txt文件并在每行中追加数据_C++_Iostream_Ifstream_Ofstream - Fatal编程技术网

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

C++ C++;读取txt文件并在每行中追加数据,c++,iostream,ifstream,ofstream,C++,Iostream,Ifstream,Ofstream,我想打开一个文件,并在每一行的末尾附加一个字符串 我有以下代码: #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 *arg

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

我有以下代码:

#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";
  }
}
#包括
#包括
#包括
使用名称空间std;
//argv[1]输入文件
//要添加到每行末尾的argv[2]字符串
//argv[3]输出文件
int main(int argc,char*argv[]){
ifstream打开_文件(argv[1]);
如果(!打开_文件){

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

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

在使用这一行代码之前,将
\r
str
的末尾修剪掉:

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

new\u file只是一个提示:阅读文件并将每行
push\u back()
添加到
std::vector
,然后将所需文本追加到每行。最后,将所有行写回文件。修复!非常感谢。你是对的。我所做的只是添加了:str.erase(str.size()-1);很高兴它有帮助。欢迎使用Stackoverflow:)