-2

how can i delete a whole line just by searching a single word in that line? for example: "i want to delete this line" (this is the sentence in the line) and i will only search the delete word and the rest of the word in that line will be delete?

here's my code

string deleteline;
string line;

ifstream fin;
fin.open("example.txt");
ofstream temp;
temp.open("temp.txt");
cout << "Enter word: ";
cin >> deleteline;


while (getline(fin,line))
{
    if(line != deleteline)
    temp << line << endl;
}
temp.close();
fin.close();
remove("example.txt");
rename("temp.txt","example.txt");
Keii
  • 39
  • 1
  • 7
  • 3
    Use [`std::string::find()`](https://en.cppreference.com/w/cpp/string/basic_string/find) or `std::regex` to check if a particular word or pattern appears in a line. – πάντα ῥεῖ Jan 09 '19 at 10:58
  • check out this answer: https://stackoverflow.com/questions/26576714/deleting-specific-line-from-file – TVK Jan 09 '19 at 11:00
  • @TVK i'm getting this kind of error "terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::replace: __pos (which is 18446744073709551615) > this->size() (which is 3)" – Keii Jan 09 '19 at 11:08
  • @πάνταῥεῖ i'll check it . thanks – Keii Jan 09 '19 at 11:09

2 Answers2

0

You can use the following algorithm:

  • Find where the line starts.
  • Find where the line ends.
  • Copy the character after the line into the file in position where the line starts. Repeat until the read position reaches the end of the file.
  • Resize the file to match the old length minus the length of the removed line.

Or the following:

  • Read the source file line by line.
  • If the line doesn't what you're searching for, then copy it into a new file.
  • Repeat until end of the source file.
  • Move the new file over the old.

The latter algorithm may be slower since it copies also the beginning of the file, but safer in case the operation is interrupted.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • There's no standard C++ way of resizing a file. Your second option is better. If efficiency is a concern then the program needs to be redesigned – john Jan 09 '19 at 11:07
  • 1
    @john Yes there is: `std::filesystem::resize_file`. The second option is better, as I explain in the answer. – eerorika Jan 09 '19 at 11:08
  • OK, I stand corrected. Haven't got round to looking at `std::filesystem` yet. – john Jan 09 '19 at 11:16
-2

Please tokenize the line using sstringstream to match the word with expected token and then write the line in a new file