user13471674
user13471674

Reputation:

find and delete whole line in file c++

I have a file with content separated by ';' like this

JACK;Basketball;Afternoon
JACK;Football;Morning
JOE;Basketball;Morning
JIM;Football;Morning
KEN;Gym;Morning
MARK;Gym;Morning

So I have this code

void deleteCourseData(string courserName, string courserType, string courseTime) {
   ifstream myfile;
   myfile.open("file.csv");
   ofstream temp;
   temp.open("temp.txt");
   string line;
   while (getline(myfile, line))
   {
        if(line.substr(0, courserName.size()) != courserName)
           temp << line << endl;
   }
   myfile.close();
   temp.close(); 
   remove("file.csv");
   rename("temp.txt", "file.csv");
}

This code searching courserName and deleting all having same name datas.

So, I want to search all datas "courserName, courserType, courseTime" and just delete that data's whole line.

Upvotes: 0

Views: 351

Answers (1)

dreamlax
dreamlax

Reputation: 95325

You can simply concatenate the three parameters together into a single string, and check for that, e.g.:

void deleteCourseData(string courserName, string courserType, string courseTime)
{
    // additional scope introduced to control the lifetime of myfile and temp
    {
        ifstream myfile("file.csv");
        ofstream temp("temp.txt");

        string line;
        string targetLine = courserName + ";" + courserType + ";" + courseTime;
        while (getline(myfile, line))
        {
           if (line != targetLine)
                temp << line << endl;
        }
    }

    remove("file.csv");
    rename("temp.txt", "file.csv");
}

Upvotes: 1

Related Questions