c - strcmp 如何用于二维数组?

标签 c multidimensional-array strcmp

我正在尝试查看 strcmp 函数在 C 中如何为二维数组工作。假设我已经使用二维数组读取了 4 个字符串。数组中的“4”是字符串的个数,数组中的“20”是字符串的最大长度。我应该要求用户输入对象二维数组中的对象,但我对其进行了硬编码以使您更容易理解这个问题。

二维数组声明为

char objects[4][20] = {{Can},
                       {Laptop},
                       {Bag},
                       {Board}};


//The above code is the 2d array containing four strings

int i;
char target[5][20];

printf("Enter the object you want to search for: \n");
scanf("%s", &target);


int check = 0;
check = strcmp(target, objects);
//printf("Check: %d\n", check);//I was trying to print check itself to know 
//what the value actually is

if (check == 0)
{
    printf("Yes the object you searched is among the list");
}
else
{
    printf("No sorry, the object you searched is not among the list");
}

请让我知道我是否做错了检查,因为输出显示每当我搜索“Can”时该对象不在列表中,但它会打印出该对象在列表中每当我搜索任何Can 之后列表中的其他对象。

最佳答案

看来你的意思是下面的

char objects[][20] = { "Can", "Laptop", "Bag", "Board" };
const size_t N = sizeof( objects ) / sizeof( *objects );

char target[20] = "Bag";

size_t i = 0;

while ( i < N &&  !( strcmp( objects[i], target ) == 0 ) ) i++;

if ( i != N)
{
    printf("Yes the object you searched is among the list");
}
else
{
    printf("No sorry, the object you searched is not among the list");
}

即判断给定字符串是否存在于字符串的二维字符数组中。

关于c - strcmp 如何用于二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46799624/

相关文章:

c - 泛型和按大小而不是按类型进行转换

c - 为什么即使我反转了两个参数,这个函数调用仍然有效?

java - 检查二维数组是否锯齿状

c - 替换字符串中的单词

c - C 中的 If 语句总是返回 false

c - 从c程序构建可执行程序

c - 读写互斥

python - 多维数组,使用范围,同时设置开始、停止和步骤?

python - 在 Python 列表中生成不在同一索引中重复的随机值

c - 空字符串的 strcmp