bob323
Jul 15th, 2001, 12:58 PM
I've just written some rather shody code (but it does the job) and was wondering if anyone could suggest some improvements to it, I find this helps me get better!
The program should open the file and read in as many names, and sins as are available inside.
To do this dynamically I created a person class with two private variables, name, and sin and created a pointer to realloc. There are a few things that I am unhappy with in this code though, for one when I reallocate I do it at the beginning of the loop therein always creating one unneeded person, in addition I also have to do a second getline at the end of every loop or else it won't read properly.
//create a person
Person *People = new Person [1];
long int sin;
//read in the first line
while(infile.getline(line, 128)){
//reallocate space for next person
realloc(People, sizeof(Person));
//set the name using the first line
People[person].SetName(line);
//collect the sin
infile >> sin;
People[person].SetSin(sin);
//output all details
People[person].PrintPerson();
//unknown necessary??
infile.getline(line, 128, '\n');
//increment the array counter
person++;
}
The file looks like this:
Bob Johal
12345678
...
Any suggestions??
The program should open the file and read in as many names, and sins as are available inside.
To do this dynamically I created a person class with two private variables, name, and sin and created a pointer to realloc. There are a few things that I am unhappy with in this code though, for one when I reallocate I do it at the beginning of the loop therein always creating one unneeded person, in addition I also have to do a second getline at the end of every loop or else it won't read properly.
//create a person
Person *People = new Person [1];
long int sin;
//read in the first line
while(infile.getline(line, 128)){
//reallocate space for next person
realloc(People, sizeof(Person));
//set the name using the first line
People[person].SetName(line);
//collect the sin
infile >> sin;
People[person].SetSin(sin);
//output all details
People[person].PrintPerson();
//unknown necessary??
infile.getline(line, 128, '\n');
//increment the array counter
person++;
}
The file looks like this:
Bob Johal
12345678
...
Any suggestions??