字符数组查找 用类实现

来源:百度知道 编辑:UC知道 时间:2024/06/24 01:32:35
5. 假设一个班级所有学生的名单组成一个字符串类型的数组,如sting names[]={“张三”,“李四”,“王五”,“”……},其中人数不定,要求在给定的数组中查找指定的某一位学生,如“赵六”。如能找到则给出该学生所在数组的位置,如找不到给出“查无此人”信息。编一个基于面向对象的程序,功能要求由类来实现,类的主要功能有:
1) 接受某个班级学生名单所组成的数组和要查找的学生姓名;
2) 按照指定的姓名进行查找,如果能找到,返回该学生在数组中的位置;如果找不到,返回-1(查无此人);
3) 在主函数中实现类的功能。

已经编译运行。

#include <iostream>
#include <string>
using namespace std;

class Student
{
public:
Student(){ name=""; }
void InputName() //输入学生姓名
{
cin>>name;
}
friend int FindName(Student stu[],string sname,int num);
private:
string name; //学生姓名
};

int FindName(Student stu[],string sname,int num) //查找学生姓名
{
int i;
for (i=0; i<num; i++)
{
if (sname == stu[i].name)
{
return i+1;
}
}
return -1;
}

void main()
{
int num,i;
cout<<"输入学生总数:";
cin>>num;
Student *stu=new Student[num];

cout<<"输入"<<num<<"个学生姓名:";
for (i=0; i<num; i++)
{
stu[i].InputName();//输入
}

string sname;
cout<<"输入要查找的学生姓名:";
cin>>sname;