如何进行 `if` 检查输入的单词是否等于 C 中字符串列表中的某个单词?

How can I do an `if` check if the typed word is equal to some word in a string list in C?

如何 if 检查键入的单词是否等于 C 中字符串列表中的某个单词? 示例:

#include <stdio.h>

int main(){

char input[20];
char* strings[] = {"apple","banana"};

printf("try to hit one of my favorite fruits:\n");
scanf("%s", input);

if(input == strings[]){
     printf("you got it right %s is one of my favorite fruits!", input);
}else{
    printf("you missed");
     }
}

我想这就是您要找的。

#include<stdio.h>
#include<string.h> //you need string.h to use strcmp()

int main(){

char input[20];
char* strings[] = {"apple","banana"};

printf("try to hit one of my favorite fruits:\n");
scanf("%s", input);
for(int i=0;i<2;i++){ //2 is the length of the array
if(strcmp(input,strings[i])==0){ //strcmp() compares two strings
     printf("you got it right %s is one of my favorite fruits!", input);
     return 0;
}
}
printf("you missed");
}

要在 C 中比较字符串,必须使用 strcmp() 函数:

bool hit = false;
for (size_t i = 0; !hit && i < sizeof strings / sizeof *strings; ++i)
{
  hit = strcmp(input, strings[i] == 0);
}

if (hit)
{
  printf("You hit one of my favorites!\n");
}
else
{
  printf("You missed, too bad.\n");
}

请注意,一旦找到命中,循环就会结束,然后在循环之后检查 hit 变量以确定要打印的正确消息。

您还应该检查 scanf() 没有失败,因此它有一个 return 值。

if语句中的条件

f(input == strings[]){

在语法上是不正确的,至少因为下标运算符 strings[].

中缺少索引

但是如果你会像例子那样在句法上正确地写条件

f(input == strings[0]){

没有意义,因为比较的是两个指针而不是字符串。

要比较两个字符串,您应该使用标准 C 字符串函数 strcmp

您可以编写一个单独的函数来检查字符串指针数组中是否存在字符串。

例如

#include <stdio.h>
#include <string.h>

int is_present( const char * s1[], size_t n, const char *s2 )
{
    size_t i = 0;
    
    while ( i < n && strcmp( s1[i], s2 ) != 0 ) ++i;
    
    return i != n;
}

int main(void) 
{
    char input[20];
    const char * strings[] = { "apple", "banana" };
    const size_t N = sizeof( strings ) / sizeof( *strings );

    printf( "try to hit one of my favorite fruits:\n" );
    scanf( "%s", input );

    if( is_present( strings, N, input ) ){
        printf("you got it right %s is one of my favorite fruits!", input);
    }else{
        printf("you missed");
    }
    
    return 0;
}

程序输出可能看起来像

try to hit one of my favorite fruits:
apple
you got it right apple is one of my favorite fruits!