我是c ++的初学者,所以请耐心等待。我被要求编写一个程序,其中一个功能是从文件中删除一个记录,并使用数组将其放在另一个文件中(因此计数器的大小未知)。我尝试了很多不同的方法但无济于事。现在我收到abort()
错误,我真的不知道该做什么或修复什么。非常需要你的帮助。
void DeletePatient ()
{
ifstream infile;
infile.open ("patients.txt");
ofstream outfile;
outfile.open ("deletedpatients.txt");
int i=0, flag=0, counter=0, deleteID, deletedindex;
//Read contents into array
while(!infile.eof())
{
infile>>IDnumber[i]>> FirstName [i] >> LastName [i] >> PhoneNumber [i] >> Nationality [i];
i++;
counter++;
}
if ( !infile )
cout << "Error opening file\n";
else
{
cout<<"Enter ID number of patient to be deleted\n";
cin >> deleteID;
for(i=0;i<counter;i++)
{
if(deleteID==IDnumber[i])
{
infile >> IDnumber [i] >> FirstName [i] >> LastName [i] >> PhoneNumber [i] >> Nationality [i];
outfile << IDnumber [i] <<" "<< FirstName [i]<<" " << LastName [i]<<" " << PhoneNumber [i]<<" " << Nationality [i];
flag++;
for(deletedindex=i; i<counter; deletedindex++)
{
IDnumber[deletedindex]=IDnumber[deletedindex+1];
FirstName[deletedindex]=FirstName[deletedindex+1];
LastName[deletedindex]=LastName[deletedindex+1];
PhoneNumber[deletedindex]=PhoneNumber[deletedindex+1];
Nationality[deletedindex]=Nationality[deletedindex+1];
}
}
}
infile.close();
if(flag==0)
cout<<"User does not exsist\n";
else
{
ofstream updatefile;
updatefile.open("patients.txt");
for ( i=0 ; i < counter; i++ ) //update file
{
updatefile << IDnumber [i] <<" "<< FirstName [i]<<" " << LastName [i]<<" " << PhoneNumber [i]<<" " << Nationality [i];
}
cout << "Patient is deleted" << endl;
updatefile.close();
}
}
outfile.close ();
}
答案 0 :(得分:1)
让我们看一下这个循环的条件:
for(deletedindex = i; i < counter; deletedindex++)
循环内部i
和counter
都没有被修改,所以一旦你进入,你就不会离开(没有未定义的行为) - 无限循环
也许,你的意思是:
for(deletedindex = i; deletedindex + 1 < counter; deletedindex++)
无论如何,您的代码需要严格的重构 - 使用具有这些属性的一个对象数组,还要考虑使用std::vector
。