有一学生小玉(xiaoyu)信息包含学号(num)、姓名(name)、性别(sex)、年龄(age)、电话(tel)等信息,要求设以一个结构体(Student)用于存储该学生小玉的信息,实现学生信息的输入和显示。 说明: (1)使用结构体实现学生信息的存储 (2)按照序号顺序排列学生信息 (3)实现按照序号查找学生信息
时间: 2024-01-04 15:04:31 浏览: 128
好的,我可以帮你解决这个问题。以下是使用C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
typedef struct {
int num;
char name[20];
char sex[5];
int age;
char tel[15];
} Student;
int num_of_students = 0;
Student students[MAX_STUDENTS];
void add_student() {
if (num_of_students >= MAX_STUDENTS) {
printf("The storage is full!\n");
return;
}
printf("Please input the student's information:\n");
printf("Number: ");
scanf("%d", &students[num_of_students].num);
printf("Name: ");
scanf("%s", students[num_of_students].name);
printf("Sex: ");
scanf("%s", students[num_of_students].sex);
printf("Age: ");
scanf("%d", &students[num_of_students].age);
printf("Telephone: ");
scanf("%s", students[num_of_students].tel);
num_of_students++;
printf("Added successfully!\n");
}
void show_students() {
if (num_of_students == 0) {
printf("There is no student information!\n");
return;
}
printf("All students' information:\n");
printf("Num\tName\tSex\tAge\tTel\n");
for (int i = 0; i < num_of_students; i++) {
printf("%d\t%s\t%s\t%d\t%s\n", students[i].num, students[i].name, students[i].sex, students[i].age, students[i].tel);
}
}
void sort_students() {
for (int i = 0; i < num_of_students - 1; i++) {
for (int j = i + 1; j < num_of_students; j++) {
if (students[i].num > students[j].num) {
Student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
printf("Sorted successfully!\n");
}
void search_student() {
int num;
printf("Please input the student's number: ");
scanf("%d", &num);
for (int i = 0; i < num_of_students; i++) {
if (students[i].num == num) {
printf("The student's information:\n");
printf("Num\tName\tSex\tAge\tTel\n");
printf("%d\t%s\t%s\t%d\t%s\n", students[i].num, students[i].name, students[i].sex, students[i].age, students[i].tel);
return;
}
}
printf("The student is not found!\n");
}
int main() {
int choice;
while (1) {
printf("\n-----Menu-----\n");
printf("1. Add student\n");
printf("2. Show all students\n");
printf("3. Sort students by number\n");
printf("4. Search student by number\n");
printf("5. Exit\n");
printf("Please input your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_student();
break;
case 2:
show_students();
break;
case 3:
sort_students();
break;
case 4:
search_student();
break;
case 5:
exit(0);
default:
printf("Invalid choice, please input again!\n");
break;
}
}
return 0;
}
```
在这个程序中,我们定义了一个 `Student` 结构体,用于存储学生的信息。然后我们使用一个数组 `students` 来存储多个学生的信息,同时用一个变量 `num_of_students` 来记录学生信息的数量。
程序主要分为以下几个部分:
1. `add_student()`:用于添加新的学生信息。
2. `show_students()`:用于显示所有学生的信息。
3. `sort_students()`:用于按照学生的序号顺序对学生信息进行排序。
4. `search_student()`:用于按照学生的序号查找学生信息。
在 `main()` 函数中,我们使用一个 `while` 循环来显示菜单,并根据用户的选择执行不同的操作。其中,`exit(0)` 用于退出程序。
希望这个程序能够解决你的问题,如果你还有任何疑问,请随时问我。
阅读全文