dimanche 29 mars 2015

Saving string to class attribute using character pointer in C++


I'm having difficulty trying to take in inputs using cin, saving them to a few variables, and then constructing a class. When I put in the first input, instead of waiting for the next input, the program loop infinitely and keeps displaying the prompt over and over.


The class is:



class person {
public:
char *name;
char *email;
int phone;
// constructor that uses the parameters to initialize the class properties
person(char *cName, char *cEmail, int iPhone) {
name = new (char[32]); // acquiring memory for storing name
email = new (char[32]); // acquiring memory for storing email
strcpy(name, cName); // initialize name
strcpy(email, cEmail); // initialize email
phone = iPhone; // initialize phone
}
virtual ~person() {
delete[] name;
delete[] email;
}
};


And the input and constructor call is as follows:



char* nameIn = new (char[32]); // acquiring memory for storing name
char* emailIn = new (char[32]);
int iPhoneIn;

cout << "Enter name, email, and phone:\n";

cin >> *nameIn;
cin >> *emailIn;
cin >> iPhoneIn;

person* newPerson = new person(nameIn, emailIn, iPhoneIn); //create node



Aucun commentaire:

Enregistrer un commentaire