I have made a custom class, Person, which holds information about persons, from a job perspective.
class Person
{
char* _name;
char* _lName;
char* _department;
int _age, _salary;
public:
Person(char* name, char* lName, char* department, int age, int salary);
Person(void);
~Person(void);
char* getFName(){return _name;};
char* getLName(){return _lName;};
char* getDepartment(){return _department;};
int getSalary(){return _salary;};
friend std::ostream &operator<<(std::ostream &cout, Person &person);
friend std::istream &operator>>(std::istream& is, Person &person);
};
What I wish to accomplish, is to stream data into this class, using cin, in the form of a comma separated char*.
The cin overload:
std::istream &operator>>(std::istream &is, Person &person)
{
char* tmp="";
is >> tmp;
int i=0;
int number=0;
char** dataArray=new char*;
dataArray[0]="";
while(tmp[i]!= '\0')
{
if(tmp[i]==',')
{
number++;
dataArray[number]="";
}
else
dataArray+=tmp[i];
i++;
}
person._name=dataArray[0];
person._lName=dataArray[1];
person._department=dataArray[2];
person._salary=(int)dataArray[3];
person._age=(int)dataArray[4];
return is;
}
However, the program stops, with an error, at;
is >> tmp;
I haven't manipulated istreams at all before, the error is probably due to faulty reasoning. Help would be appreciated.
You need to specify the size here:
char** dataArray=new char*;
I think you need:
char** dataArray=new char*[5];
You leak the memory for this variable. You seem to be manipulating the elements of this array as if they are std::string
, but they are simple char arrays. You need to allocate and reallocate them. To avoid all that issues use std::vector
and std::string
. Your errors have nothing to do with operator<<
itself.