我的字符串比较函数返回 false,即使字符串位于数组中

问题描述 投票:0回答:1

对于以下代码,当我搜索高帽时,我没有得到所需的结果(即找到) 相反,找不到输出。 我认为这与 char 数组在幕后的工作方式有关,任何人都可以向我解释这一点。

#include <string.h>
#define MAX_LIMIT 20

int main(void)
{
    char strin[MAX_LIMIT];
    char numbers[6][10] = {"battleship","boat","cannon","iron","thimble","top hat"};
    printf("enter string to search:");
    scanf("%s", &strin);

    for(int i=0;i<6;i++)
    {
        if(strcmp(numbers[i],strin)==0)
        {
            printf("found\n");
            return 0;
        }
    }
    printf("not found\n");
    return 1;
}```
arrays c char strcmp
1个回答
0
投票

scanf
中的
scanf("%s", &strin);
将从 stdin 读取数据,直到出现终止空字节
('\0')

当您输入“top hat”时,

scanf
将读取“top”而不是“top hat”。

我运行了你的代码,

strin
的值为“top ;�$���,����”。数字中没有这样的字符串。

strin
是一个char数组。char数组的名称是内存地址。我认为使用
strin
代替
&strin
更好。

如果我想在数字中搜索“高帽”,我会使用

fgets
而不是
scanf
。这是我的代码。效果很好。

#include <stdio.h>
#include <string.h>
#define MAX_LIMIT 20

int main(void)
{
    char strin[MAX_LIMIT];
    char numbers[6][10] = {"battleship","boat","cannon","iron","thimble","top hat"};
    printf("enter string to search:");
//    scanf("%5s", &strin);
    fgets(strin, sizeof(strin), stdin);
    strin[strcspn(strin, "\n")] = '\0';


    for(int i=0;i<6;i++)
    {
        if(strcmp(numbers[i],strin)==0)
        {
            printf("found\n");
            return 0;
        }
    }
    printf("not found\n");

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.