This is the instruction for my assignment:
Write a program to process stock data. The stock data should be read from a text file containing the following data: stock code, stock name, amount invested (999.99), shares held, and current price.As each stock is read, insert it into a binary search tree (BST). The BST should be ordered on the stock code. (1½ marks)
After building the BST, display a menu with the following options: (1 mark)
(a) Display the BST in inorder traversal. Each display should contain an appropriate heading and column captions; (1 mark)
(b) Search for a stock using the stock code and print the data for the stock; (1 mark)
(c) Modify data for an existing stock; (2 marks)
(d) Write the data back to the file you used to build the tree in the beginning of the program execution, and stop the program. (1½ marks)
I have written the code but currently having problem with loading the list of stock stored in the file. The function of loading the code and inserting the stock into a binary tree are as follows:
Code:
void load(void)
{
STOCK *info;
FILE *inp;
inp=fopen("stock.txt","r");
if(!inp)
{
printf("Cannot open file.\n");
exit(1);
}
//free any previously allocatd memory
while(root)
{
info=root->left;
free(info);
root=info;
info=root->right;
free(info);
}
root=NULL;
printf("\nLoading File.\n");
while(!feof(inp))
{
info=(STOCK*)malloc(sizeof(STOCK));
if(!info)
{
printf("Out of memory");
exit(1);
}
while((fscanf( inp," %[^\n]", &info->stockCode))!=EOF)
{
fscanf( inp," %[^\n]", &info->stockName);
fscanf( inp," %[^\n]", &info->amountInvested);
fscanf( inp," %[^\n]", &info->sharesHeld);
fscanf( inp," %[^\n]", &info->currentPrice);
root=stree(root, info);
}
}
if (fclose(inp)==EOF)
{
printf ("Error in closing file.\n");
exit (105);
}
else
{
printf ("File is successfully loaded.\n");
}
system("pause");
system("cls");
}
Code:
STOCK *stree(STOCK *r, STOCK *n)
{
if(!r)
{
n->left=NULL;
n->right=NULL;
if(!root)
return n;
if(strcmp(n->stockCode,root->stockCode) <0)
root->left=n;
else
if(strcmp(n->stockCode,root->stockCode) >0)
root->right=n;
return n;
}
if(strcmp(r->stockCode, n->stockCode) <0)
r=stree(r,r->right,n);
else
if(strcmp(n->stockCode,root->stockCode) >0)
r=stree(r,r->left,n);
return r;
}
I couldn't find the mistake where it only print out the last item. Any advise?
I attached the full coding as well.
Thanks.