33,311
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<string>
using namespace std;
class Base //基类
{ protected:
string name; //姓名
string school; //学校
string profession; //专业
string telephone; //电话
string birthday; //生日
public:
Base() //构造函数
{ name = "no name";
school = "no school";
profession = "no profession";
telephone = "no telephone";
birthday = "no birthday";
}
virtual ~Base() //虚析构函数
{}
static void TrimLine(char *sbuf) //静态函数处理字符串换行与回车符
{ while(*sbuf != '\0')
if(*sbuf == '\r'||*sbuf == '\n')
{ *sbuf = '\0';
break;
}
sbuf++;
}
virtual string GetName() = 0; //纯虚函数
virtual bool Input(FILE *fp) = 0; //纯虚读入函数
virtual void Print() = 0; //纯虚打印函数
};
class Student:public Base //学生类
{ public:
Student()
{}
string GetName()
{ return name;
}
bool Input(FILE *fp)
{ char sbuf[100];
fgets(sbuf,100,fp);
TrimLine(sbuf);
name = sbuf;
fgets(sbuf,100,fp);
TrimLine(sbuf);
school = sbuf;
fgets(sbuf,100,fp);
TrimLine(sbuf);
profession = sbuf;
fgets(sbuf,100,fp);
TrimLine(sbuf);
telephone = sbuf;
fgets(sbuf,100,fp);
TrimLine(sbuf);
birthday = sbuf;
return true;
}
void Print()
{ cout<<"name: "<<name<<endl;
cout<<"school: "<<school<<endl;
cout<<"profession: "<<profession<<endl;
cout<<"telephone: "<<telephone<<endl;
cout<<"birthday: "<<birthday<<endl;
}
};
int main()
{ FILE *stream;
stream = fopen("StudentDirectory.txt","r"); //打开StudentDirectory.txt文件
if(stream == NULL)
{ cout<<"Can't open the file."<<endl;
return 0;
}
Base *base[4];
string sbuf;
int index = 0;
while(index<4) //读入
{ base[index] = new Student();
base[index]->Input(stream);
index++;
}
fclose(stream);
while(true)
{
cin>>sbuf; //输入要查找的学生信息
if(sbuf == "0")
break;
for(int i=0;i<index;i++)
{ if(base[i]->GetName() == sbuf) //找到并输出学生信息
base[i]->Print();
}
cout<<endl;
}
for(int i=0;i<index;i++) //清理
{ delete base[i];
}
return 0;
}