Home > Software engineering >  How to delete strings from a file containing multiple lines in C ?
How to delete strings from a file containing multiple lines in C ?

Time:11-05

I tried this code but it deletes data if a file has only one line. When file contains multiple lines this code throws an exception. How to fix it?

int main()
{
string deleteline;
    string line;

    ifstream fin;
    fin.open("Test1.txt");
    ofstream temp1;
    temp1.open("temp.txt");
    deleteline="|start|";



    while (getline(fin,line))
    {
        line.replace(line.find(deleteline), deleteline.length(), "");
        temp1 << line << endl;

    }

    temp1.close();
    fin.close();
    remove("Test-1.txt");
    rename("temp.txt", "Test-1.txt");


}

CodePudding user response:

Could you please try this one ?

#include <iostream>
#include <fstream>
#include <string>



int main ()
{
  std::ifstream in_file("input.txt");
  std::ofstream out_file("output.txt"); 
 
  std::string str;
  const std::string removed_str = "|start|";

  while (std::getline(in_file, str)) {
    std::size_t ind = str.find(removed_str);
    std::cout << str << std::endl;
    if(ind != std::string::npos)
    {
      str.erase(ind, removed_str.length());
    }

    std::cout << str << std::endl;

    out_file << str << std::endl;
  }

    
  return 0;
}

input.txt

Line1 |start| 
Line2   |start|
Line3 Line1 Line2 |start|

output.txt

Line1  
Line2   
Line3 Line1 Line2 
  •  Tags:  
  • c
  • Related