How to delete a line in a textfile using c++?

The program i wrote can run but did not work. I want to delete a line from the textfile "StaffList.txt" but when i cin the name, for example "Ben". After the program ran finished and i open the textfile, the name "Ben" and the whole line is still inside the textfile! I have created the "temp.txt" file before i run the program. Need help!!

//information inside the "StaffList.txt"
James S1325685J 1258 0
Peter S8856325K 5265 0
Ben S1025639Z 8525 0
Ken S9052365B 7410 0
Marry S9352654I 7532 0
John S7754852H 9963 0
Jenny S7042525L 7453 0
May S1256985G 1596 0
Betty S1135565K 5636 0
Kyle S9545530A 1234 100

//c++
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;

int main()
{
string line, name;
cout << "Please Enter the name of record you want to delete: ";
cin >> name;
ifstream myfile;
myfile.open("StaffList.txt");
ofstream temp;
temp.open("temp.txt");
while (getline(myfile, line))
{
if (line != name)
temp << line << endl;
}
cout << "The record with the name " << name << " has been deleted if it exsisted" << endl;
myfile.close();
temp.close();
remove("StaffList.txt");
rename("temp.txt", "StaffList.txt");

system("pause");
return 0;
}
The line is not the name.

Since the name is the first part of line you may use substr:

http://www.cplusplus.com/reference/string/string/substr/

like so: if (line.substr(0, name.size()) != name)
It worked!! Thank you :)
Topic archived. No new replies allowed.