-
got this running but...
I just created this class and I've got it running in main however it never escapes the first function call. help.
Code:
//Class definition for personType
#ifndef PERSON_TYPE_H
#define PERSON_TYPE_H
const int N_S = 20;
const int D_S = 500;
class personType
{
public:
personType();
void setName();
int setAge();
void setDescription();
~personType();
private:
char* name;
int age;
char* description;
};
#endif
#include <iostream>
#include "PersonType.h"
using namespace std;
personType::personType()//Default constructor
{
name = NULL;
age = 0;
description = NULL;
}
void personType::setName()
{
char temp[N_S];
cout << "Please enter the person's name." << endl;
cout << ">>>";
for(int i = 0;i < N_S;i++ )
cin >> temp[i];
cout << endl;
return;
}
int personType::setAge()
{
int temp;
cout << "Please enter the person's age." << endl;
cout << ">>>";
cin >> temp;
if(!cin)
{
cin.clear();
cin.ignore(100, '\n');
cout << "Invalid input.";
}
age = temp;
return 0;
}
void personType::setDescription()
{
char temp[D_S];
cout << "Please type the person's description." << endl;
cout << ">>>";
for(int i = 0;i < D_S;i++)
cin >> temp[i];
for(int j = 0; j < strlen(temp); j++)
description[j] = temp[j];
cout << endl;
return;
}
personType::~personType()
{
delete []name;
delete []description;
}
#include <iostream>
#include "PersonType.h"
using namespace std;
int main()
{
personType person;
person.setName();
cout << " ";
person.setAge();
cout << " ";
person.setDescription();
return 0;
}
-
It will, but first you need to type in N_S (20) nonwhitespace characters.
The string handling is way off, anyway. If at all possible, use the std::string class and many problems will go away. setName does not even attempt to set the name member of the class, whereas setDescription tries to, but fails to allocate any memory for the description member.
-
okay I'll look at the two string functions but I have to use C-strings for the upcoming class I'm taking. lost all my class code c++ basic and advanced in one big drive scrub.
-
1. I will recommend you to read about accessors and mutators regarding classes. As setName() is only allowed to set the name of private member, so you should better get the name from main and pass it to that function, which will be the real object oriented approach.
2. Use std::strings or std::vector instead.....
3. If you don't know about these, you can also use cin.getline().
-