deleteContact() function: can't delete contact

I am writing a contact list program and I wrote a deleteContact() that.. deletes a contact. However I don't know how to delete a contact so that it actually gets deleted inside the actual file.

1
2
3
4
5
6
7
8
9
10
11
12
void deleteContact(fstream& file) {
    string name;
    cout << "Enter name of who you want to delete: " << endl;
    cin >> name;
    string line;
    while(getline(file, line)) {
        if (line.find(name, 0) != string::npos) {
            // What would I put here?
        }
    }
    
}
Hi Jakeculp,

Without knowing much about advanced file editing in C++, I'd suggest the simplest solution would simply be to:

1) Read the file buffer into a std::string vector. Something like,
1
2
3
4
5
6
7
8
9
  std::vector<std::string> contacts;
  std::string line;
  if (file.is_open())
  {
    while (std::getline (myfile,line))
    {
      contacts.push_back(line);
    }
  }


2) Search the contacts vector for the specified contact.
3) If the contact is found, delete it from the contacts vector.
4) Destructively re-write the file with the new data.

Again, I'm no expert, this just seems the most obvious way to do it.
Topic archived. No new replies allowed.