Yes, I have looked in the forums for answers and have found plenty, and am asking about what I could not find. And yes, this is homework, but I need help and my professor has not responded thus far... now on to business.
Description of Goal: Make a Set Data Structure using a singly Linked List. The goal is to read word by word from a text file, and (if it hasn't already been added to the list) add it to the linked list. Simple, right?
My problem: I am not getting the correct outputs. I suspect that my pointers are being screwed up and that is what is messing up my comparisons.
My text file (myFile.txt): "hippo cat dog giraffe hippo kitty rhino cat"
My program output:
"Word is: hippo
ADD1111: hippo
Word is: cat
Compare: cat to: cat
Word is: dog
Compare: dog to: dog
Word is: giraffe
Compare: giraffe to: giraffe
Word is: hippo
Compare: hippo to: hippo
Word is: kitty
Compare: kitty to: kitty
Word is: rhino
Compare: rhino to: rhino
Word is: cat
Compare: cat to: cat
First run: cat"
Result analysis: The program is simply assigning whatever word is read to the head of Linked List. And only compares the buffer to the buffer. This is probably do to the pointers, but I hate pointers and cannot figure it out.
#include<stdlib.h>
#include<stdio.h>
struct list_el {
char *val;
struct list_el * next;
};
typedef struct list_el item;
void main() {
item * curr, * head, * curr2;
int i, isIn = 0, first =0;
FILE* tFile;
tFile = fopen("myFile.txt", "r"); // assume the file exists and has data
char *buf[35];
head = NULL;
//curr= head;
while (!feof(tFile)){
fscanf(tFile,"%s",buf);
printf("Word is: %s \n",buf);
isIn = 0;
if(first==0){ //if first elem in list
first=1;
printf("ADD1111: %s\n ", buf);
curr = (item *)malloc(sizeof(item));
curr->val = buf;
curr->next = head;
head = curr;
}
else{
curr2=curr;
while(curr){
if (curr->val == buf){
printf("Compare: %s to: %s\n", curr->val, buf);
isIn = 1;
break;
}
curr = curr->next;
}
curr=curr2;
if(isIn == 0){
printf("ADD: %s\n ", buf);
curr = (item *)malloc(sizeof(item));
curr->val = buf;
curr->next = head;
head = curr;
}
}
// curr = head;
}
curr=head;
while(curr) {
printf("First run: %s\n", curr->val);
curr = curr->next;
}
}
Any help would be appreciated.