以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:
要在您的C++学生管理系统中添加按学号删除学生记录的功能,您可以按照以下步骤进行:
- 编写新的成员函数
DeleteStudentByID(int findnum): 这个函数将检查文件中是否存在具有指定学号的学生记录,并将其删除。
void Student::DeleteStudentByID(int findnum) {
fstream file("student.txt");
ofstream temp("temp.txt");
string line;
int num;
bool found = false;
// 读取原始文件并写入临时文件,跳过要删除的记录
while (file >> num) {
getline(file, line); // 读取剩余的行
if (num != findnum) {
temp << num << " " << line << endl; // 写入临时文件,除了要删除的记录
} else {
found = true; // 标记找到要删除的记录
}
}
file.close();
temp.close();
if (found) {
remove("student.txt"); // 删除原始文件
rename("temp.txt", "student.txt"); // 重命名临时文件为原始文件名
cout << "已成功删除学号为 " << findnum << " 的学生记录!" << endl;
} else {
cout << "未找到学号为 " << findnum << " 的学生记录。" << endl;
}
}
- 在
main()函数的while (true)循环中添加新的选项: 在循环的选项列表中添加一行输出语句,并在switch语句中添加case 7:部分。
int main() {
// ... 省略其他代码 ...
while (true) {
cout << "***欢迎进入学生管理系统***" << endl;
cout << "1. 录入学生信息" << endl;
cout << "2. 浏览全部学生记录" << endl;
cout << "3. 按学号查找学生记录" << endl;
cout << "4. 按学号修改出生日期" << endl;
cout << "5. 按学号修改学生成绩" << endl;
cout << "6. 退出系统" << endl;
// 添加新的选项
cout << "7. 按学号删除学生记录" << endl;
cout << "请选择功能:";
cin >> choice;
switch (choice) {
// ... 省略其他case ...
case 7:
cout << "请输入要删除的学生学号:";
cin >> findnum;
stu.DeleteStudentByID(findnum);
break;
// ... 省略其他case ...
}
}
return 0;
}
通过这些更改,您的系统将能够让用户通过输入学号来删除对应的学生记录,并从文件中永久移除这些信息。记得在实际代码中替换 stu 和 findnum 为相应的变量名。
