0

Is there any way I could delete the entire line from a text file when a certain word is found?

This can be done using the function ignore()?

I try to do this with next code:

string line;
while(!f.eof()) {
    getline(f, line);
    if(line.find(cnp) == line.npos) {
        g1 << line << endl;
    }
}

But every time the program runs the new list is saved, could I do this to save all the changes, from all the runs?

Casey
  • 8,686
  • 9
  • 52
  • 79
SDM
  • 1
  • 1
  • 1
    *"...every time the program runs"* - what program ? Include a proper [mcve] and maybe we can help. I can tell you, however, that I cannot think of a single scenario where a stream `.ignore()` method is any help whatsoever. – WhozCraig Apr 05 '21 at 17:29
  • It looks like your code is writing to `g1`. Unless the file associate with `g1` is relinked to the file associated with `f`, then you are not changing the file associated with `f`. – William Pursell Apr 05 '21 at 17:52
  • `while(!f.eof()) { getline(f, line); ... }` needs to be `while(getline(f, line)) { ... }`, see [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/) – Remy Lebeau Apr 05 '21 at 18:34

1 Answers1

1

I'm not 100% sure what you're doing and what does the solution need to do with ignore. Please, provide an MRE (see @WhozCraig's comment) so that we can better understand your problem and provide better help.

Here is a solution which reads one file and writes it to the other file, but removes lines, which begin from the word "world" (words are considered to be separated by spaces):

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

int main()
{
    std::ifstream inp("inp.txt");
    std::ofstream out("out.txt");
    
    std::string line;
    while(getline(inp, line))
    {
        // If the word "world" followed by a space not found
        if(line.find("world ") == std::string::npos)
            // Then print the line to the output file
            out << line << '\n';
        // Otherwise do nothing
    }
}

Example input file (inp.txt):

hello world
world hello
goodbye world
world goodbye

Output file (out.txt):

hello world
goodbye world
Kolay.Ne
  • 1,104
  • 6
  • 16