简体   繁体   中英

How to compare string to string array?

Im trying to write a program that takes a password created by a user and compares it to an array of strings. The password has to be a word not in the array. For example: The user enters the password "about" and that word is in the array so it will return "Wrong". What i've tried dosent work, Can someone help?

Here's everything i have so far:

int main()

{
    int i;
    char dict[998][15];
    char password[30];
    size_t ind; 

    FILE *fp = fopen("dictionary.txt", "r");

    if (fp != NULL) 
    {
      
        for (ind = 0; fgets(dict[ind], sizeof dict[0], fp) && ind < sizeof dict / sizeof dict[0]; ind++)
        {
            dict[ind][strcspn(dict[ind], "\n")] = '\0'; 
        }

  
    }
    else
    {
        printf("Error opening file");
    }
    fclose(fp);
     printf("Please enter Password: ");
     scanf("%s",password);
    //Checking if password is in array.
       for (size_t i = 0; i < ind; i++) 
       {
             if (!strcmp(password, dict[i])) 
             {
                 printf("Wrong");
             }
             else
             {
                 printf("Correct");
             }
       }
   
}

You are writing "Correct" or "Wrong" for every checked word in the dictionary. You have to stop checking if the word appears in the dictionary, and if all words are checked and the password does not appear, then print "Correct".

A possible implementation that just prints the result and exits would be something like:

printf("Please enter Password: ");
scanf("%s", password);
//Checking if password is in array.
for (size_t i = 0; i < ind; i++)
{
    if (!strcmp(password, dict[i]))
    {
        printf("Wrong");
        return -1;
    }
}
printf("Correct");
return 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM