strcmp如何为2d数组工作?

时间:2017-10-17 21:37:31

标签: c multidimensional-array strcmp

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

2d数组声明为

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之后列表中的其他对象。

1 个答案:

答案 0 :(得分:2)

看来你的意思是以下

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

那就是你要确定给定的字符串是否存在于字符串的二维字符数组中。