Search code examples
c++filetemp

Why does my delete string attempt fail


I have been attempting to make my own version of this example:

Delete a specific line from a file

But I cannot get mine to work correctly. My current goal for the program is to delete the string and its information (which is the string below the first string), which it does; however, it also adds an additional space to the first line so that it looks like this:

(First Line)


(Second Line) This should be the first line.

Here is the code:

infile = ifstream;
outfile = ofstream;
cout<< "What string would you like to delete";
cin>>delstr;
infile.clear();
infile.seekg(0, ios::beg);

ofstream tempfile;
tempfile.open("temp.txt",std::ios::app);

while(delreset == true){

    if(delstr == fLine){
        getline(infile, fLine);

        cout<<"String deleted.\n";
        delreset = false;

        while(fLine != nothing){
            getline(infile, fLine);
            tempfile<<fLine<<"\n";
        }

        tempfile.close();
        infile.close();
        outfile.close();
        remove("example.txt");
        rename("temp.txt","example.txt");

    }else{

        tempfile<<fLine<<endl;
        getline(infile, fLine);

    }
    outfile.flush();
    delreset = true;
}

I deleted what I could to make it an abridged version of the actual program, hopefully I didn't edit anything so that it doesn't make sense.


Solution

  • What with a simpler version:

    ...  // prepare everything as before
    while(getline(infile, fLine)) {
        if(delstr == fLine) {   // if line found do nothing
            cout<<"String deleted.\n";
            getline(infile, fLine);  // EDIT: and read and ignore the following line 
        }
        else 
            tempfile<<fLine<<"\n";  // else copy it 
    }
    ...  // here infile was read and tempfile contains the filtered output 
    

    With this approach you could even write directly to the outfile.

    By the way cin>>delstr; only takes a word. It stops at the first blank and ignores trailing blanks. You could use getline(cin, delstr); instead.