我正在尝试通过 id 从 C++ 中的文件中删除特定行,这是我的代码:
void deleteRow()
{
ifstream inDb("files/students.dat", ios::in);
if(!inDb)
{
cerr << "File could no be opened!\n";
}
cout << countRowsOfDb() << " records." << endl;
Student *studentsArray[countRowsOfDb()];
int n = 0;
while(inDb >> id >> name >> grade >> points >> type)
{
studentsArray[n] = new Student(id, name, grade, points, type);
n++;
}
inDb.close();
for(int i = 0; i < countRowsOfDb(); i++)
{
cout << studentsArray[i]->id << " " << studentsArray[i]->name << " " << studentsArray[i]->grade << " "
<< studentsArray[i]->points << " " << studentsArray[i]->type << "\n";
}
cout << "\nWhich one you would like to delete? Enter an id: ";
string term;
cin >> term;
ofstream outDb("files/students.dat", ios::out);
if(!outDb)
{
cerr << "File could no be opened!\n";
}
for(int i = 0; i < countRowsOfDb(); i++)
{
if(studentsArray[i]->id != term)
{
outDb << studentsArray[i]->id << " " << studentsArray[i]->name << " " << studentsArray[i]->grade << " "
<< studentsArray[i]->points << " " << studentsArray[i]->type << "\n";
}
}
outDb.close();
cout << "\nObject deleted!\n";
}
我创建了一个输入文件流,然后获取所有行,使其成为对象数组并在屏幕上显示它们,然后通过输入 id 询问要删除哪个,当我输入 id 时,我试图把所有这些数组的元素只有没有具有相同 id 的元素,但它不起作用,之后文件中没有任何内容。有任何想法吗?