简体   繁体   English

如何将字符串与字符串数组进行比较?

[英]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".例如:用户输入密码“about”并且该单词在数组中,因此它将返回“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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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