-1

Below is a snippet from my code. I want to remove the string that the user enters from the current file.

void del(std::string filename){
  using namespace std;
  string x;
  cout << "What item do you wanna delete";
  cin >> x;
  ofstream myfile;
  myfile.open(filename);
  }

I am thinking that I can locate "x" in the file and then remove it, but I'm not sure as to how to go about it.

Zen
  • 1
  • 2
  • 1
    The most common way is to read the file, and then write a new file without the deleted part. And possibly rename the files afterwards. – BoP May 28 '22 at 17:34
  • @BoP thank you for your comment, how do i write a new file without the deleted part – Zen May 28 '22 at 18:02
  • @Zen open the selected file using `ifstream`, and create a new file with a different name using `ofstream`. Then read items from the original file in a loop, writing only items to the new file that don't match the item to delete. Then close both files, delete the old file, and rename the new file to the old name. – Remy Lebeau May 28 '22 at 18:28

0 Answers0