C语言定义一个结构体,在数组中实现删除
时间: 2024-04-27 21:21:46 浏览: 7
好的,可以为您提供以下示例代码:
```c
#include <stdio.h>
struct student {
int id;
char name[20];
int score;
};
int main() {
struct student stu_array[10] = {
{1, "Tom", 80},
{2, "Jerry", 90},
{3, "Lily", 85},
{4, "Lucy", 78},
{5, "Bob", 92},
{6, "Alice", 88},
{7, "John", 81},
{8, "Mike", 79},
{9, "Kate", 87},
{10, "Jack", 93}
};
int delete_id;
printf("Please input the id of the student you want to delete: ");
scanf("%d", &delete_id);
int found = 0;
for (int i = 0; i < 10; i++) {
if (stu_array[i].id == delete_id) {
found = 1;
for (int j = i; j < 9; j++) {
stu_array[j] = stu_array[j + 1];
}
break;
}
}
if (found) {
printf("Delete successfully!\n");
for (int i = 0; i < 9; i++) {
printf("id:%d, name:%s, score:%d\n", stu_array[i].id, stu_array[i].name, stu_array[i].score);
}
} else {
printf("Student not found!\n");
}
return 0;
}
```
以上代码定义了一个名为 `student` 的结构体,其中包含学生的ID、姓名和分数。然后创建了一个包含10个学生信息的数组。
接着,程序会提示用户输入要删除的学生的ID,并通过循环遍历数组查找该学生。如果找到了该学生,程序会将该学生后面的所有学生信息向前移动一位,并输出删除后的学生数组。如果未找到该学生,则输出“Student not found!”。