C语言如何筛选出结构体内编号为0000的专业
时间: 2024-01-21 20:20:16 浏览: 22
假设有一个结构体类型为`Student`,包含以下成员:
```c
struct Student {
char name[20];
char major[20];
char id[5];
};
```
其中,`id`表示学生的编号,长度为4个字符。
如果你想筛选出专业编号为"0000"的学生,可以使用循环遍历结构体数组,并使用`strcmp`函数比较`major`和`id`是否相等,代码如下:
```c
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
char major[20];
char id[5];
};
int main() {
struct Student students[3] = {
{"Tom", "0000", "0001"},
{"Jerry", "1111", "0002"},
{"Alice", "0000", "0003"}
};
for (int i = 0; i < 3; i++) {
if (strcmp(students[i].major, "0000") == 0) {
printf("Name: %s, Major: %s, ID: %s\n", students[i].name, students[i].major, students[i].id);
}
}
return 0;
}
```
输出结果为:
```
Name: Tom, Major: 0000, ID: 0001
Name: Alice, Major: 0000, ID: 0003
```
这里使用了`strcmp`函数来比较字符串相等,需要包含头文件`string.h`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)