Click to See Complete Forum and Search --> : array of structures


ssawant1
June 7th, 2002, 09:20 AM
The following program is suppose to read a data file which
has first name (15), last name (15) & age delimited by a space.
It then need to be sorted in the order of age.

I am declaring a structure, then reading
the file record by record and storing it to the structure.
After populating the structure I am trying to print the same
(not yet sorted). The problem is it prints the age, but does not print the name.

Please help



/* The following program reads 5 first names , last names, ages into an array of structures.
The names are stored in a "data.dat" file. */

#include <iostream.h>
#include <stdio.h>
#include <fstream.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>


struct personalInfo
{
char lName[15];
char fName[15];
short age;
};


personalInfo* getData(); //Function Prototype

void main()
{
personalInfo *ptr; // ptr is a pointer to the personalInfo structure
ptr = getData();
cout << ptr->age << " " << ptr->fName;
/* at this point it prints the age, but the fName is not displayed */
}//end of main


personalInfo* getData()

{
personalInfo detail[5];
personalInfo *detailPtr;
detailPtr = detail;

static ifstream fin;
fin.open("data.dat");

if (!fin)
{
cout << "\nCannot open data.dat.. \n";
exit(1);
} //end of if (!fin)

char temp[4];
char stemp[16];
for (short n = 0; n < 5; n++)
{
fin.getline(stemp,15);
strcpy(detail[n].lName, stemp);

fin.getline(stemp, 15);
strcpy(detail[n].fName,stemp);

fin.ignore();
fin.getline(temp,4);

detail[n].age = atoi(temp);
fin.ignore();

cout << endl <<"NAME " << detail[n].lName << " " << detail[n].fName << " " ;
cout << detail[n].age << endl;
}

fin.close();
return detailPtr;

}//end of personalInfo* getData()

AlanGRutter
June 7th, 2002, 09:39 AM
I'm not quite sure why you're only getting the age without running the program.

Have you debugged the getData() function to verify that it is reading the file properly and poulating the array correctly.

Also , you may want to note that the ptr pointer in main is assigned the result of the getData() function (a pointer to the first element of your array). However, your array is a local variable within the getData() function which will go out of scope when getData() returns, hence invalidating any of its contents and any references to it.

Regards
Alan

ssawant1
June 7th, 2002, 09:53 AM
Thankyou Alan, let me try some other method,
in any case I shall post the updated code