检查项目是否在C中的数组中

Alb*_*ert -2 c arrays string char

我正在检查一个项目是否在C中的数组中,使用for循环遍历数组中的每个项目并将其与用户输入一一比较。

int main()
{
    char birds[] =
    {
        [0] = "a",
        [1] = "b",
        [2] = "c",
        [3] = "d",
        [4] = "e",
        [5] = "f",
        [6] = "g",
        [7] = "h"
    };
    int birdfound;
    int i;
    printf("Enter bird:");
    scanf("%c", &birdfound);
    //printf("%c", birdfound);
    for(i=0; i<8; i++)
    {
        //printf("Y");
        if(birdfound == birds[i]){
            printf("Bird in array, found at position %d\n", i);
        }
    }
    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我知道,问题出在分支逻辑之内,因为某种原因,它无法将字符输入与数组中的任何字符进行比较。因此,输出为空,程序仅结束。

Bla*_*aze 5

您正在为分配字符串文字char。尝试以下方法:

char birds[] =
    {
        [0] = 'a',
        [1] = 'b',
        [2] = 'c',
        [3] = 'd',
        [4] = 'e',
        [5] = 'f',
        [6] = 'g',
        [7] = 'h'
    };
Run Code Online (Sandbox Code Playgroud)

另外,int birdfoundmust be char birdfound,否则scanf("%c", &birdfound);是未定义的行为,因为您告诉它char它确实是一个int


在所有可能的情况下,您的意图很可能是使用字符串代替,您可以通过以下方式实现:

char *birds[] = // note the "*"
    {
        [0] = "foo",
        [1] = "bar",
    };
Run Code Online (Sandbox Code Playgroud)

然后您像这样阅读它:

char birdfound[20]; // space for 19 chars and the null terminator
scanf("%19s", &birdfound); // read up to 19 chars
Run Code Online (Sandbox Code Playgroud)

并找到它像这样:

if (!strcmp(birdfound, birds[i])) {
    printf("Bird in array, found at position %d\n", i);
}
Run Code Online (Sandbox Code Playgroud)