Code:
#include <iostream>
#include <vector>
#define MAX 100
class Student{
public:
Student(){
studage=0;
studid=0;
}
int GetStudentId(){
return studid;
}
int GetStudentAge(){
return studage;
}
char* GetStudentName(char* dest,int length){
if(name[0]!='\0'){
strncpy(dest,name,length);
}
return dest;
}
bool SetData(int id,char* student,int age){
if(student[0]!='\0'){
strncpy(name,student,sizeof(name));
studid=id;
studage=age;
return true;
}
return false;
}
private:
char name[256];
int studid,studage;
};
int main(void){
int id=1;
char buf[256],buf2[256];
char option;
std::vector<Student> Students;
std::vector<Student>::iterator it;
Student temp;
do{
std::cout<<"\n1. View students.\n2. Register new students\n3. Search students\n4. Exit this program\n--> ";
option=std::cin.get();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
switch(option){
case '1':
if(!Students.empty()){
it = Students.begin();
for(it=Students.begin();it!=Students.end();it++){
printf("Id: %i -- Name: %s -- Age: %i\n",it->GetStudentId(),
it->GetStudentName(buf,256),it->GetStudentAge());
}
}
else{
printf("There are no students.\n");
}
printf("Press enter to continue.");
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
break;
case '2':
printf("Enter student's name:");
std::cin.getline(buf,256,'\n');
printf("Enter student's age:");
std::cin.getline(buf2,10,'\n');
temp.SetData(id,buf,strtol(buf2,NULL,10));
Students.push_back(temp);
id++;
printf("Press enter to continue.");
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
break;
case '3':
printf("Search by 1)id 2)name 3)age : ");
option=std::cin.get();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
printf("Search: ");
std::cin.getline(buf,256,'\n');
switch(option){
case '1':
if(!Students.empty()){
it = Students.begin();
for(it=Students.begin();it!=Students.end();it++){
if(it->GetStudentId()==strtol(buf,NULL,10)){
printf("Id: %i -- Name: %s -- Age: %i\n",it->GetStudentId(),
it->GetStudentName(buf2,256),it->GetStudentAge());
break;
}
}
}
else{
printf("There are no students.\n");
}
break;
case '3':
if(!Students.empty()){
it = Students.begin();
for(it=Students.begin();it!=Students.end();it++){
if(it->GetStudentAge()==strtol(buf,NULL,10)){
printf("Id: %i -- Name: %s -- Age: %i\n",it->GetStudentId(),
it->GetStudentName(buf2,256),it->GetStudentAge());
}
}
}
break;
default:
if(!Students.empty()){
it = Students.begin();
for(it=Students.begin();it!=Students.end();it++){
if(strstr(it->GetStudentName(buf2,256),buf)!=NULL){
printf("Id: %i -- Name: %s -- Age: %i\n",it->GetStudentId(),buf2,it->GetStudentAge());
}
}
}
else{
printf("There are no students.\n");
}
break;
}
printf("Press enter to continue.");
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
break;
case '4':
return 0;
break;
default:
printf("This is not a valid option.\n");
}
} while(true);
return 0;
}