我正在尝试查看 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/