replace line in a file C++

后端 未结 4 1704
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 15:40

I\'m trying to find a way to replace a line, containing a string, in a file with a new line.

If the string is not present in the file, then append it to the file.

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 16:37

    Although I recognize that this is not the smartest way to do it, the following code reads demo.txt line by line and searches for the word cactus to replace it for oranges while writing the output to a secondary file named result.txt.

    Don't worry, I saved some work for you. Read the comment:

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    
    int main()
    {
      string search_string = "cactus";
      string replace_string = "oranges";
      string inbuf;
      fstream input_file("demo.txt", ios::in);
      ofstream output_file("result.txt");
    
      while (!input_file.eof())
      {
          getline(input_file, inbuf);
    
          int spot = inbuf.find(search_string);
          if(spot >= 0)
          {
             string tmpstring = inbuf.substr(0,spot);
             tmpstring += replace_string;
             tmpstring += inbuf.substr(spot+search_string.length(), inbuf.length());
             inbuf = tmpstring;
          }
    
          output_file << inbuf << endl;
      }
    
      //TODO: delete demo.txt and rename result.txt to demo.txt
      // to achieve the REPLACE effect.
    }
    

提交回复
热议问题