Hi, I'm new to this forum and C++... I created this thread to post problems if I have one and I hope you will help me...
Exercise:
Write a class member that holds information about a member of a sports club. Member details include name, surname, year of entry into the club and the ID number(of course this is a simplified example).
Write Display method to display information about member. The main program creates two objects of type member: information about both objects is read by the keyboard. Then you must display data using the Display method...
#include <iostream>
usingnamespace std;
class Member
{
private:
char cName[20];
char cSurname[20];
int iEntry_year;
int iID;
public:
Member()
{
cout << "Enter name: ";
cin.getline(cName, 20);
cout << "Enter surname: ";
cin.getline(cSurname, 20);
cout << "Enter entry year: ";
cin >> iEntry_year;
cout << "Enter ID number: ";
cin >> iID;
}
void display()
{
cout << "Information on member: " << endl;
cout << cName << endl << cSurname << endl << iEntry_year << endl << iID << endl;
}
};
int main()
{
Member member1;
member1.display();
Member member2;
member2.display();
Member member3;
member3.display();
return 0;
};
The big question is, why can I enter cName only on first object??? The second object goes directly to cSurname... Can someone explain to me why??
Can I use constructor this way, or should I make a new function for the input information?
Thanks in advance...
I would definitely suggest putting the user input in a separate function (perhaps not even on the class itself) and using the input to pass to a constructor or something.
getline reads until it finds a new line character. cin >> iID; reads the next integer and leaves the new line character in the stream.
When you next time call getline it will read what was left on the line.
One way could be to always use getline and use stringstream to read the numbers out from it. It becomes a little bit more complicated but if you know how stringstream work it's not hard to do.
Another way could be to always call getline until you have read non-empty string.
If you do any of this you probably wan to create functions so you don't have to write the same over and over.
add this line after your iID input line: cin.ignore(20); cin.clear(); //This will clear the input buffer so getline will work properly on the next iteration.
Here's a function I wrote for this, because I always hated trying to remember how to get a ranged random number, lol:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int randomRange( int _Min, int _Max )
{
//include this library
//#include <time.h>
//include this call in the code before hand. ( main() )
//srand( unsigned ( time (NULL) ) );
//add 1 to the max, so it's included in the result.
_Max += 1;
int x = _Min + ( rand() % ( _Max - _Min ) );
return x;
}