|
-
December 1st, 2008, 12:01 AM
#1
Count word frequency with linked list
I'm supposed to code a program in C++ that queries a user for a file name. That file is then to be scanned and each word is to be placed into a node within a linked list. If the word is already in the list the counter of the respective node should increase by one and there should be no duplicate nodes.
I have coded the program to the best of my ability and got it to compile, however, it crashes when I run it... I've been scratching my head over it for hours and cant seem to get anywhere with it.
Code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct node
{ char word[50]; // word being inputted
int count; // word frequency
node *next; // Pointer to next node
};
node *start = NULL;
void add_node(char nWord[50]);
int main()
{ char cWord[50];
char cFile[30];
FILE *pfTextfile;
node *temp; //temporary node to store data
node *current; //node to traverse with
int TravFlag = 0; //Flag to help traverse
cout << "Enter the file you wish to have searched:\n";
cin >> cFile;
// open file
pfTextfile = fopen(cFile, "r");
while(!feof(pfTextfile))
{ TravFlag=0;
//empty cWord
for (int i=0; i<50; i++)
{ cWord[i]='\0';
}
current = start; //node that points to beginning
// make temp first node
if (start == NULL)
{start = temp;
start->word[50]=cWord[50];
start->count=1;
}
else if(start!=NULL) //if theres already a node
{ while(TravFlag==0)//Loop to Traverse
{if(current->word==cWord)//If current node is same word
{current->count=current->count+1;//count increases by 1
TravFlag=1; //set flag to end loop
}
else if(current->word!=cWord&¤t->next==NULL)
{//end of the list
add_node(cWord);
TravFlag=1;
}
else
current = current->next; //move to next node
}
}
}
//Print em
current=start;
do
{if(current==NULL)
cout<<"End of list."<<endl;
else
{ cout<< "The word "<<current->word<<" appears "<<current->count<<" times."<<endl;
current=current->next;
}
}
while(current!=NULL);
}
void add_node(char nWord[50])
{ node *temp, *temp2; // Temporary pointers
temp = new node;
temp->word[50]=nWord[50];
temp->count=1;
temp->next = NULL;
// Set up link to this node
if (start == NULL)
start = temp;
else
{ temp2 = start;
while (temp2->next != NULL)
{ temp2 = temp2->next; // Move to next node
}
temp2->next = temp;
}
}
I'm pretty new to this stuff so any help at all would be fantastic!
Thanks!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|