我在做一个学生管理系统。除了Delete Student Info函数之外,所有的函数都工作得很好。在学习C++语言方面,我完全是个新手。
当我尝试使用Delete函数时,结果会是这样的,就像一个循环:

这是我的删除代码:
void student::deleted()
{
system("cls");
fstream file, file1;
int found = 0;
string snum;
cout<<"\t\t\t\t-------------------------------------------\t\t\t"<<endl;
cout<<"\t\t\t\t---------Delete Student Information--------\t\t\t"<<endl;
file.open("Records.txt", ios::in);
if (!file)
{
cout << "\n\t\t\tNo information is available.";
file.close();
}
else
{
cout <<"\nEnter Student Number you want to remove: ";
cin >> snum;
file1.open("Records1.txt", ios::app | ios::out);
file >> student_num >> name >> bday >> address >> gender >> degree >> year;
while (!file.eof())
{
if(snum != student_num)
{
file1 << " " << student_num << " " << name << " " << bday << " " << address << " " << gender << " " << degree << " " << year ;
} else
{
found==0;
cout <<"\n\t\t\tSuccessfully Deleted.";
}
}
file1 >> student_num >> name >> bday >>address >> gender >> degree >> year ;
if (found == 0)
{
cout <<"\n\t\t\tStudent Number not found.";
}
file1.close();
file.close();
remove("Records.txt");
rename("Records.txt", "NewRecords.txt");
}除了这个删除功能之外,所有的功能都在我的程序上运行。我希望你能用我还不知道的知识来启发我。
发布于 2021-12-04 04:28:45
基本上,您的整个while循环的结构都是错误的。试试更多像这样的东西:
void student::deleted()
{
system("cls");
cout<<"\t\t\t\t-------------------------------------------\t\t\t"<<endl;
cout<<"\t\t\t\t---------Delete Student Information--------\t\t\t"<<endl;
ifstream inFile("Records.txt");
if (!inFile)
{
cout << "\n\t\t\tCan't open file.";
return;
}
ofstream outFile("NewRecords.txt");
if (!outFile)
{
cout << "\n\t\t\tCan't create new file.";
return;
}
cout << "\nEnter Student Number you want to remove: ";
string snum;
cin >> snum;
bool found = false;
while (inFile >> student_num >> name >> bday >> address >> gender >> degree >> year)
{
if (snum == student_num)
{
found = true;
}
else if (!(outFile << " " << student_num << " " << name << " " << bday << " " << address << " " << gender << " " << degree << " " << year)
{
cout << "\n\t\t\tCan't write to new file.";
outFile.close();
remove("NewRecords.txt");
return;
}
}
if (!inFile.eof())
{
cout << "\n\t\t\tCan't read information.";
outFile.close();
remove("NewRecords.txt");
return;
}
outFile.close();
inFile.close();
if (!found)
{
cout <<"\n\t\t\tStudent Number not found.";
remove("NewRecords.txt");
return;
}
if (rename("Records.txt", "OldRecords.txt") != 0)
{
cout <<"\n\t\t\tCan't backup old file.";
remove("NewRecords.txt");
return;
}
if (rename("NewRecords.txt", "Records.txt") != 0)
{
cout <<"\n\t\t\tCan't rename new file.";
rename("OldRecords.txt", "Records.txt");
return;
}
remove("OldRecords.txt");
cout <<"\n\t\t\tSuccessfully Deleted.";
}https://stackoverflow.com/questions/70222897
复制相似问题