C++/String Problem
Expert: Prince M. Premnath - 3/8/2007
Question
-------------------------------------------
The text above is a follow-up to ...
-----Question-----
Hi!
We had a string problem in C++, we were told to create some sort of a lesson plan that receives data from the user and displays them. I'm having a problem in storing multiple full names of the students in the program. The name to be entered includes the first name space the middle name space and the family name. How can I store this 3-worded name in order for me to retrieve them later in displaying?
-----Answer-----
Dear ralph!
Actually the name is splitted into three parts ( First name , initial , and Family name ) all this three elementary items are composed as a STUDENT NAME using a class name!
here ill present you a simple code regarding your expectation , you are free to alter this code as per your need !
#include<iostream.h>
class name
{
private:
char fname[20];
char init;
char lname[20];
friend class stud;
};
// since the members are private we have to provide mechanism to access in other class using friend function!
class stud
{
private:
class name a;
char id[20];
public:
void getinfo();
void putinfo();
};
void stud :: getinfo()
{
cout<<"Enter Student First name";
cin>>a.fname;
cout<<"Enter Student initial";
cin>>a.init;
cout<<"Enter Student Family name";
cin>>a.lname;
cout<<"Enter student ID";
cin>>a.id;
}
void stud :: putinfo()
{
cout<<a.fname;
cout<<" ";
cout<<a.init<<" ";
cout<<a.lname<<endl;
}
void main()
{
stud st[10];
for( int i = 0 ; i < 2 ; i++)
{
st[i].getinfo();
}
for( i = 0 ; i < 2 ; i++)
{
st[i].putinfo();
}
}
Note; program will input information about three students ( as per the format you expected ) and displays Three names !
Thanks and regards !
Prince M. Premnath
Question again...
Sir what if the person will enter the number of student to be stored in the program? Does this also apply in the previous program you gave?
AnswerDear Ralph!
The program what i had given U is of course self explanatory , it will just read names about 3 students you can alter the program to process store name for n students !
Jut i edited the code what i given previously !
class stud
{
private:
class name a;
char id[20];
public:
void getinfo();
void putinfo();
};
void stud :: getinfo()
{
cout<<"Enter Student First name";
cin>>a.fname;
cout<<"Enter Student initial";
cin>>a.init;
cout<<"Enter Student Family name";
cin>>a.lname;
cout<<"Enter student ID";
cin>>a.id;
}
void stud :: putinfo()
{
cout<<a.fname;
cout<<" ";
cout<<a.init<<" ";
cout<<a.lname<<endl;
}
void main()
{
int n;
cout<<"Enter number of students ";
cin>>n;
stud st[n];
for( int i = 0 ; i < n ; i )
{
st[i].getinfo();
}
for( i = 0 ; i < n ; i )
{
st[i].putinfo();
}
}
Note ! This program will now work for n students !
Thanks and regards!
Prince M. Premnath.