【问题标题】:Checking if an item is in an array in C [closed]检查项目是否在C中的数组中[关闭]
【发布时间】:2019-05-27 14:43:24
【问题描述】:

我正在检查一个项目是否在 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;
}

我知道问题在于分支逻辑,因为由于某种原因,它无法将字符输入与数组中的任何字符进行比较。因此,输出什么都没有,程序就结束了。

【问题讨论】:

  • 你应该看看你的编译器告诉你什么,在线编译器告诉你:ideone.com/uyYSrk
  • 这段代码不是有效的 C 代码,不能干净地编译,所以这是你的问题。
  • 你听说过strchr()吗?
  • "a",带双引号,不是char,而是char *'a',加上简单的引号,是char
  • @mouviciel: "a"/*readonly*/char[2]; 'a'int

标签: c arrays string char


【解决方案1】:

您正在将字符串文字分配给您的chars。试试这个:

char birds[] =
    {
        [0] = 'a',
        [1] = 'b',
        [2] = 'c',
        [3] = 'd',
        [4] = 'e',
        [5] = 'f',
        [6] = 'g',
        [7] = 'h'
    };

另外,int birdfound 必须是 char birdfound,否则 scanf("%c", &amp;birdfound); 是未定义的行为,因为你告诉它它是 char,而实际上它是 int


您的意图很可能是在说完所有事情后使用字符串,您可以通过这种方式实现:

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

然后你这样读:

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

然后像这样找到它:

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

【讨论】:

    【解决方案2】:

    您已经得到了答案,但是,还有另一种方法可以实现相同的目标,而无需进入导致问题的场景。

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

    参考: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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-13
      • 2017-12-29
      • 2012-06-30
      • 2021-10-27
      • 1970-01-01
      • 2012-12-07
      • 2014-03-28
      • 2012-03-31
      相关资源
      最近更新 更多