有n个学生信息(包括学号,姓名,成绩),按学号升序存储在一个结构体数组中,分别用两个函数完成完成按“学号”、“姓名”两个属性进行查找,找出其在数组中是第几个元素。如果不在数组中,则输出“查无此人”。
时间: 2024-04-29 09:21:18 浏览: 14
以下是C++代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
struct Student {
int id;
string name;
int score;
};
int findById(Student students[], int n, int targetId) {
for (int i = 0; i < n; i++) {
if (students[i].id == targetId) {
return i;
}
}
return -1;
}
int findByName(Student students[], int n, string targetName) {
for (int i = 0; i < n; i++) {
if (students[i].name == targetName) {
return i;
}
}
return -1;
}
int main() {
int n;
cout << "请输入学生人数:";
cin >> n;
Student students[n];
cout << "请输入学生信息(学号、姓名、成绩):" << endl;
for (int i = 0; i < n; i++) {
cin >> students[i].id >> students[i].name >> students[i].score;
}
int choice;
cout << "请选择查找方式(1:按学号查找;2:按姓名查找):";
cin >> choice;
if (choice == 1) {
int targetId;
cout << "请输入要查找的学号:";
cin >> targetId;
int index = findById(students, n, targetId);
if (index != -1) {
cout << "该学生在数组中的位置为:" << index + 1 << endl;
} else {
cout << "查无此人" << endl;
}
} else if (choice == 2) {
string targetName;
cout << "请输入要查找的姓名:";
cin >> targetName;
int index = findByName(students, n, targetName);
if (index != -1) {
cout << "该学生在数组中的位置为:" << index + 1 << endl;
} else {
cout << "查无此人" << endl;
}
} else {
cout << "无效的选择" << endl;
}
return 0;
}
```
运行结果示例:
```
请输入学生人数:3
请输入学生信息(学号、姓名、成绩):
1001 张三 80
1003 李四 90
1005 王五 70
请选择查找方式(1:按学号查找;2:按姓名查找):2
请输入要查找的姓名:李四
该学生在数组中的位置为:2
```