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

时间:2019-05-27 14:43:24

标签: c arrays string char

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

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;
}

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

2 个答案:

答案 0 :(得分:4)

您正在为private void TextBox_OnEnter(object sender, EventArgs e) { var textBox = sender as TextBox; if (textBox.ReadOnly) { SelectNextControl(this.ActiveControl, true, true, true, true) } } private void txtCategory_Leave(object sender, EventArgs e) { var readOnly = string.IsNullOrWhiteSpace(txtCategory.Text) || !Category.Exists(txtCategory.Text); txtSubCategory.ReadOnly = readOnly; } 分配字符串文字。尝试以下方法:

char

此外,char birds[] = { [0] = 'a', [1] = 'b', [2] = 'c', [3] = 'd', [4] = 'e', [5] = 'f', [6] = 'g', [7] = 'h' }; 必须为int birdfound,否则char birdfound是未定义的行为,因为当它实际上是{{1}时,您会告诉它它是scanf("%c", &birdfound); }。


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

char

然后您像这样阅读它:

int

然后找到它:

char *birds[] = // note the "*"
    {
        [0] = "foo",
        [1] = "bar",
    };

答案 1 :(得分:0)

您已经找到了答案,但是,还有另一种方法可以实现相同目的,而无需进入引起问题的方案。

代码是不言自明的,带有注释。

参考:man page for strchr()

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

int main(void)  // correct signature
{
    char *str = "abcdefgh";                   // define the string in which to search
    char check = -1;                          // to hold the user input
    if (scanf("%c", &check) != 1) {           // basic sanity check with scanf
        exit (-1);
    }

    char * res = strchr (str, check);          // check whether the input is preset or not

    if (!res) {                                // return null pointer, means not found
        printf("not Found!!");
    }
    else {                                     // not null, match found
        printf("Found %c\n", *res);
    }
    return 0;
}