5
我的C++程序出現問題...我的整個程序是學生姓名,成績和年齡的數據庫,當用戶想要刪除1學生。下面是代碼:C++刪除文件中的文本行
void deletestudentdata()
{
string name, grade, tname;
int age, x=0; // x - "counter" to check if user entered wrong name
system("cls");
cout << "Enter name of the student you want to erase from database" << endl;
cin >> tname;
ifstream students("students.txt");
ofstream temp("temp.txt"); // temp file for input of every student except the one user wants to delete
while(students >> name >> grade >> age)
{
if(tname!=name){ // if there are students with different name, input their data into temp file
temp << name << ' ' << grade << ' ' << age << endl;
}
if(tname==name){ // if user entered correct name, x=1 for later output message that the user data has been deleted
x=1;
}
}
students.clear(); // clear eof and fail bits
students.seekg(0, ios::beg);
students.close();
temp.close();
remove("students.txt");
rename("temp.txt","students.txt");
if(x==0){ // x was set to 0 at start, so if it didn't change, it means user entered the wrong name
cout << "There is no student with name you entered." << endl;
}
else{ // x is not 0, it means user entered the correct name, print message that students data has been deleted
cout << "Student data has been deleted." << endl;
}
}
它的工作原理,但問題是,我進入學生數據,當我想通過此功能,它不會刪除它刪除它,我首先要關閉該程序,然後重新打開該程序,然後調用該函數,以便刪除學生數據。
我該如何更改它,以便在輸入後立即刪除學生數據,而無需先關閉程序?
你可以更精確的執行它,例如:''我輸入學生數據'',怎麼樣? – Synxis
我在VS2012中運行它。沒有看到任何問題。 – shivakumar
假設您在程序運行期間將學生姓名列表存儲在其他地方,而不僅僅是在文件中,並且您還需要從那裏刪除學生。 (或者清除列表,並在您複製姓名時將其填入。) –