Parsing a file is when you read a file to collect information from the file. In
ID: 3559982 • Letter: P
Question
Parsing a file is when you read a file to collect information from the file. In this assignment, you will parse a file, and put all of the words in a Binary Search Tree (BST). You will use the BST to collect data about the number of times a word was found in the file. You should make no assumptions about which letters are in the middle (like M). The first word you encounter will be the root. If the next word is greater, put it to the right. If it is less, put it to the left. It is possible that the tree you make will be very sparse (think what happens when the first word is zebra).
Assume all words in the file are lower case (you can covert them easily anyway). I would recommend using the string library (it makes comparisons much better). After you have loaded the file into your BST, the user should be given the chance to type a word. The computer should say the number of times the word was found in the file (zero or more).
My .txt file is consist of:
apple banana banana orange cookie cookie cookie grape
Explanation / Answer
//create a file mytext.txt with contents
apple banana banana orange cookie cookie cookie grape
//write a program program.cpp
#include<stdio.h>
#include<string>
using namespace std;
struct node
{
char info[100];
struct node *left;
struct node *right;
};
node* insert(struct node* root,char *data)
{
struct node *newnode;
if(root==NULL)
{
root=(struct node*)malloc(sizeof(struct node*));
strcpy(root->info,data);
root->left=NULL;
root->right=NULL;
return root;
}
if(strcmp(root->info,data) >= 0)
root->left=insert(root->left,data);
else
root->right =insert(root->right,data);
return root;
}
void display(struct node* root)
{
if(root!=NULL)
{
display(root->left);
printf("%s ",root->info);
display(root->right);
}
return;
}
int search(struct node* root,char *input)
{
static int count=0;
if(root==NULL)
return count;
if(strcmp(root->info,input)==0)
count++;
if(strcmp(root->info,input)>=0)
search(root->left,input);
else if(strcmp(root->info,input)<0)
search(root->right,input);
}
int main()
{
char ch[100];
FILE *fptr;
struct node *root=NULL;
if((fptr=fopen("mytext.txt","r"))==NULL)
{
printf("error opening file ");
exit(1);
}
while(!feof(fptr))
{
if( fscanf(fptr,"%s",ch)==1){
printf("%s ",ch);
root=insert(root,ch);
}
}
char input[100];
printf("enter the word want to search ");
scanf("%s",input);
int found=search(root,input);
printf("number of times word to be found : %d ",found);
fclose(fptr);
//printf("tree diaplay ");
// display(root);
return 0;
}
output will be like this:
enter the word want to search
cookie
number of times word to be found : 3
[root@hss110(14:03:18) : geeksforgeeks]# ./a.out
enter the word want to search
banana
number of times word to be found : 2
[root@hss110(14:03:28) : geeksforgeeks]# ./a.out
enter the word want to search
apple
number of times word to be found : 1