Monday, July 27, 2009

How do I implement a table structure in c++?

I have student data (name,idnumber,grade) I need to be able to sort the data alphabeticaly by name.

How do I implement a table structure in c++?
Hope it helps someone,





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;string.h%26gt;





#define LINE_LEN 128





typedef struct T


{


char *data;


struct T *left;


struct T *right;


} node;





node *makeNode (char *data)


{


node *temp = (node *) malloc (sizeof (node));





temp-%26gt;data = calloc (LINE_LEN, sizeof (char));


strcpy (temp-%26gt;data, data);


temp-%26gt;left = NULL;


temp-%26gt;right = NULL;





return temp;


}





node *addNode (char *line, node *root)


{


if (root == NULL)


return makeNode (line);





if (strcmp (line, root-%26gt;data) %26lt; 0)


root-%26gt;left = addNode (line, root-%26gt;left);


else


root-%26gt;right = addNode (line, root-%26gt;right);





return root;


}





node *readFile (FILE *in_fp)


{


node *root = NULL;


char *line = (char *) calloc (LINE_LEN, sizeof (char));





while (!feof (in_fp))


{


fscanf (in_fp, "%s", line);


root = addNode (line, root);


}





return root;


}





void writeFile (node *root, FILE *out_fp)


{


if (root-%26gt;left != NULL)


writeFile (root-%26gt;left, out_fp);





fprintf (out_fp, "%s\n", root-%26gt;data);





if (root-%26gt;right != NULL)


writeFile (root-%26gt;right, out_fp);


}





void sort (char *in, char *out)


{


FILE *in_fp = fopen (in, "r");


FILE *out_fp = fopen (out, "w");


node *root = readFile (in_fp);





writeFile (root, out_fp);


fclose (in_fp);


fclose (out_fp);


}





int main (int argc, char **argv)


{


if (argc != 3)


printf ("Usage: sort unsorted_filename sorted_filename\n");


else


sort (argv [1], argv [2]);





return 0;


}


No comments:

Post a Comment