用c语言写用结构体和指针实现一个学生信息输入和查找操作的程序,要求: 1)定义一个学生信息结构体,包括学号、姓名、班级、年级等信息。 2)编写一个输入函数,传入参数为一个学生结构体数组的指针、当前存放位置、数组总长度等参数,要求接收输入的学生信息存入对应位置的结构体钟; 3)编写一个查找函数,传入参数为一个学生结构体数组的指针、要查找的学生姓名,要求跟进输入的姓名查找盖学生的其它信息,返回结构体位序; 4)编写一个主函数,先建立学生信息的结构体数组,然后用该数组调用以上函数,实现函数功能的调用,并将返回信息输出到命令行窗口。
时间: 2024-02-03 08:14:30 浏览: 48
以下是使用结构体和指针实现学生信息输入和查找操作的程序:
```c
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
struct Student {
int id;
char name[20];
int grade;
int class;
};
int input(struct Student *stu, int pos, int len) {
if (pos >= len) {
printf("Sorry, the array is full.\n");
return pos;
}
printf("Please enter the student's ID: ");
scanf("%d", &(stu + pos)->id);
printf("Please enter the student's name: ");
scanf("%s", &(stu + pos)->name);
printf("Please enter the student's grade: ");
scanf("%d", &(stu + pos)->grade);
printf("Please enter the student's class: ");
scanf("%d", &(stu + pos)->class);
return pos + 1;
}
int search(struct Student *stu, char *name, int len) {
for (int i = 0; i < len; i++) {
if (strcmp((stu + i)->name, name) == 0) {
printf("ID: %d Name: %s Grade: %d Class: %d\n", (stu + i)->id, (stu + i)->name, (stu + i)->grade, (stu + i)->class);
return i;
}
}
printf("Sorry, the student is not found.\n");
return -1;
}
int main() {
struct Student stu[MAX_SIZE];
int n = 0, pos;
char name[20];
printf("Please enter 'i' to input a student information, 's' to search a student information, and 'q' to quit.\n");
while (1) {
char c;
printf("> ");
scanf(" %c", &c);
if (c == 'i') {
pos = input(stu, n, MAX_SIZE);
if (pos > n) {
n = pos;
}
} else if (c == 's') {
printf("Please enter the student's name: ");
scanf("%s", name);
search(stu, name, n);
} else if (c == 'q') {
break;
}
}
return 0;
}
```
程序中,首先定义了一个结构体 `Student`,其中包含了学生的信息,包括学号、姓名、年级、班级。接着定义了 `input` 和 `search` 两个函数,分别用于输入学生信息和查找学生信息。在 `main` 函数中,我们首先建立一个学生信息的结构体数组,然后进入循环,等待用户输入操作指令。如果用户输入了 'i',则进入到输入学生信息的分支,调用 `input` 函数;如果用户输入了 's',则进入到查找学生信息的分支,调用 `search` 函数;如果用户输入了 'q',则退出程序。注意,在输入操作指令时,需要加上空格,否则会出现意外的错误。
程序中的 `input` 函数接收一个学生结构体数组的指针、当前存放位置、数组总长度等参数,用于接收用户输入的学生信息,并将学生信息存入对应位置的结构体中。在函数中,我们首先检查当前存放位置是否超出了数组的长度,如果超出了,则提示数组已满,否则接收用户输入的学生信息,存入对应位置的结构体中,并返回下一个存放位置。
程序中的 `search` 函数接收一个学生结构体数组的指针、要查找的学生姓名、数组总长度等参数,用于跟进输入的姓名查找该学生的其它信息,并返回结构体位序。在函数中,我们使用 `strcmp` 函数逐一比较学生姓名,如果找到了匹配的学生,则输出该学生的信息,并返回该学生在数组中的位置;如果遍历整个数组都没有找到匹配的学生,则提示该学生未找到,并返回 -1。
在 `main` 函数中,我们使用一个变量 `n` 记录当前数组中已经存储的学生信息数量,同时也记录了数组中下一个可存储学生信息的位置。在输入学生信息时,我们将 `n` 作为当前存放位置传递给 `input` 函数,并将返回值赋值给 `pos` 变量,如果返回值大于 `n`,则说明新的学生信息已经存储到了数组中,因此需要更新 `n` 的值。在查找学生信息时,我们将 `n` 作为数组总长度传递给 `search` 函数。
最后,我们在程序开始时打印了操作指令的提示信息,等待用户输入。