我的代码将我添加到列表中的每个新员工追加。我希望它替换我刚刚移除的区域。因此,如果我要删除333并添加666,我希望它成为列表中的第二个而不是最后一个
#include <stdio.h>
#define SIZE 4
struct Employ {
int ID;
int age;
double salary;
};
int main(void) {
struct Employ emp[SIZE]={{0}};
int option = 1;
int nEmp = 0;
int i;
int searchedI;
int check;
int sID;
printf("---=== EMPLOYEE DATA ===---\n\n");
while (option != 0) {
printf("1. Display Employee Information\n");
printf("2. Add Employee\n");
printf("3. Update Employee Salary\n");
printf("4. Remove Employee\n");
printf("0. Exit\n\n");
printf("Please select from the above options: ");
scanf("%d", &option);
printf("\n");
switch (option)
{
case 1:
printf("EMP ID EMP AGE EMP SALARY\n");
printf("====== ======= ==========\n");
for (i = 0; i < nEmp; i++) {
printf("%6d%9d%11.2lf\n", emp[i].ID, emp[i].age, emp[i].salary);
}
printf("\n");
break;
case 2:
printf("Adding Employee\n");
printf("===============\n");
if (nEmp == SIZE) {
printf("ERROR!!! Maximum Number of Employees Reached\n\n");
}
else {
check = 1;
while (check) {
printf("Enter Employee ID: ");
scanf("%d", &emp[nEmp].ID);
printf("Enter Employee Age: ");
scanf("%d", &emp[nEmp].age);
printf("Enter Employee Salary: ");
scanf("%lf", &emp[nEmp].salary);
if (emp[nEmp].ID < 0 || emp[nEmp].age < 0 || emp[nEmp].salary < 0) printf("\nAll number should be positive\n");
else check = 0;
}
printf("\n");
nEmp++;
}
break;
case 3: //update employee
printf("Update Employee Salary\n");
printf("======================\n");
if (nEmp == 0) {
printf("\nNo employee to update\n\n");
break;
}
do
{
check = 1;
printf("Enter Employee ID: ");
scanf("%d", &sID);
for (i = 0; i < nEmp; i++)
{
if (emp[i].ID == sID) break;
else if (i == nEmp - 1) printf("*** ERROR: Employee ID not found! ***\n");
}
if (i != nEmp) {
printf("The current salary is %.2f\n", emp[i].salary);
printf("Enter Employee New Salary: ");
scanf("%lf", &emp[i].salary);
check = 0;
printf("\n");
}
} while (check);
break;
case 4: //remove employee
printf("Remove Employee\n");
printf("===============\n");
if (nEmp == 0) {
printf("\nNo employee to remove\n\n");
break;
}
do
{
check = 1;
printf("Enter Employee ID: ");
scanf("%d", &sID);
for (i = 0; i < nEmp; i++)
{
if (emp[i].ID == sID) break;
else if (i == nEmp - 1) printf("*** ERROR: Employee ID not found! ***\n");
}
if (i != nEmp) {
check = 0;
searchedI = i;
printf("Employee %d will be removed\n\n", emp[searchedI].ID);
for (i = searchedI; i < nEmp; i++)
{
if (i != nEmp - 1) emp[i] = emp[i + 1];
else emp[i].ID = 0;
}
nEmp -= 1;
}
} while (check);
break;
case 0:
printf("Exiting Employee Data Program. Good Bye!!!\n");
break;
default:
printf("ERROR: Incorrect Option: Try Again\n\n");
break;
}
}
return 1;
}
原始列表 222 333 444
我希望列表显示 222 666 444
目前显示的结果是 222 444 666
答案 0 :(得分:0)
删除值时,可以将其替换为占位符(例如,无穷大),而不是将其从列表中删除。以后要向列表添加新值时,可以在列表中扫描该占位符,然后: