TLET
TLET

Reputation: 33

if statement doesn't work?

wordCur is a string of capital letters, and dictionary is an array of strings, no matter what I input into wordCur, I am always returned 0.

Edit: I updated the code a little bit, and added an abridged version of the rest of the program for some context. As it is shown here, it just crashes when it gets to checkValid

int main() {
    FILE *ifp;
    ifp = fopen("dictionary.txt", "r");
    int* lDist[26];
    int* lUsed[26];
    int dictLen;
    int i;
    fscanf(ifp, "%d", &dictLen);
    char dictionary[dictLen][7];
    char* letters[7];
    int scoreCur = 0;
    int scoreHi = 0;
    char wordCur[7];
    char wordHi[7];
    int isWord = 0;





//reads the dictionary into the array
for (i = 0; i < dictLen; i++) {
    fscanf(ifp, "%s", &dictionary[i]);
}
    scanf("%s", wordCur);
    isWord = checkValid(wordCur, dictLen, dictionary);
    if (isWord == 1) {
        scoreCur = calcScore(wordCur);
    }



//fclose(ifp); not sure why, but this causes a crash
return 0;
}


int checkValid (char *wordCur,int dictLen, char dictionary[dictLen]) {
    int valid = 0;
    int i;

    for (i = 0; i < dictLen; i++){
    int helper = strcmp(wordCur, dictionary[i]);
    if (helper = 0){
        valid = 1;
    }
}

Upvotes: 0

Views: 149

Answers (3)

Paul R
Paul R

Reputation: 212929

Your code should probably look more like this:

int checkValid(const char *wordCur,       // word to search for (string)
               int dictLen,               // no of entries in dictionary
               char dictionary[][7])      // dictionary (array of strings)
{
    int valid = 0;
    int i;
    for (i = 0; i < dictLen; i++)
    {
        if (strcmp(wordCur, dictionary[i]) == 0)
        {
            valid = 1;
            break;
        }
    }
    return valid;
}

Upvotes: 0

cdarke
cdarke

Reputation: 44344

wordCur is a string of capital letters, and dictionary is an array of strings

Try this:

int checkValid (const char *wordCur,int dictLen, const char *dictionary[])

By the way, you keep searching, even after you found what you are looking for, and the comaprison is wrong anyway for strings. I suggest:

for (i = 0; i < dictLen; i++){  
    if (strcmp(wordCur, dictionary[i]) == 0){  
        valid = 1;  
        break;
    }  
}  

Upvotes: 0

unwind
unwind

Reputation: 399713

wordCur is a string of capital letters

int checkValid (char wordCur,int dictLen, char dictionary[dictLen])

No, wordCur is a single character. Not a string. A string in C is represented as an array of characters, terminated by a character with the value 0. You need a pointer argument, char *wordCur.

Upvotes: 2

Related Questions