Reputation: 171
So I have created a file that has a bunch of words in it, and my program is supposed to open the file, put all of the words in an array, and then compare the strings to see if any are exact matches. It opens the file and populates the array, but the problem comes when I am trying to compare the strings.. Can anyone tell me how to go about fixing why this isn't comparing properly?
My words file:
Google Twitter Facebook Twitter gmail Flyer city
phone Google cookie Facebook Flyer grill fork silver tornado dirty
blue grill lemon
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
FILE *words;
char words_array[20][17];
int x=0;
int y=0;
int pairs = 0;
words=fopen("words.dat","r");
if(words==NULL)
printf("\n\nwords.dat was not properly opened.\n");
else
{
for(x = 0 ; x < 20 ; x++ )
{
fscanf(words,"%s",&words_array[x][y]);
}
fclose(words);
for(x = 0 ; x < 20 ; x++ )
printf("Word #%d is %s \n", x + 1, words_array[x]);
/*start of comparison*/
for(x=0;x<20;x++)
{
for(y=0;y<20;y++)
{
if (strcmp (words_array[x], words_array[x+1])==0)
pairs++;
}
/*end of comparisons*/
}
printf("%d \n",pairs);
}
return(0);
}
Output:
Word #1 is Google
Word #2 is Twitter
Word #3 is Facebook
Word #4 is Twitter
Word #5 is gmail
Word #6 is Flyer
Word #7 is city
Word #8 is phone
Word #9 is Google
Word #10 is cookie
Word #11 is Facebook
Word #12 is Flyer
Word #13 is grill
Word #14 is fork
Word #15 is silver
Word #16 is tornado
Word #17 is dirty
Word #18 is blue
Word #19 is grill
Word #20 is lemon
0
Upvotes: 2
Views: 5307
Reputation: 44921
You are only comparing the current row with the next. Change the loop with strcmp to:
for(x=0; x<20; x++) {
for(y=x+1; y<20; y++) {
if (strcmp (words_array[x], words_array[y])==0)
pairs++;
}
}
This will find five pairs in your sample data:
Google
Twitter
Facebook
Flyer
grill
On a side note you might want to add a defined constant for the number of rows at the beginning of the program (between the #includes and main) so you don't have to replace the 20
everywhere if you want to change the number of lines read (and of course the same can be said for the word length):
#define MAXLINES 20
#define MAXLENGTH 17
and then you can use those constants everywhere you now have 20 and 17.
Upvotes: 3