简体   繁体   English

如何使用 strcmp 搜索数组中的元素

[英]How can I search an element in an array with strcmp

Animal is a struct and name is one of its attribute. Animal 是一个结构体,name 是它的属性之一。 What I want is when I write a name in scanf, it should iterate in the array uing strcmp and when it returns 0 then it should print that index in the array.我想要的是当我在 scanf 中写一个名字时,它应该使用 strcmp 在数组中迭代,当它返回 0 时它应该在数组中打印该索引。

void SearchAnimalName(Animal *animalName, uint8_t number_of_animals)
{
    char search[10];
    scanf("%s", search);

    for (int i = 0; i < number_of_animals; i++)
    {
        if (strcmp(search, (animalName + i)->name) == 0)
        {

            return animalName->name;
        }
    }
}

Your function has the return type void .您的 function 具有返回类型void

void SearchAnimalName(Animal *animalName, uint8_t number_of_animals)

That is it returns nothing and the compiler should issue a message for this return statement也就是说它什么都不返回,编译器应该为这个返回语句发出一条消息

return animalName->name;

Also it is unclear why the second parameter has the type uint8_t and at the same time you are using a variable of the type int within the for loop.同样不清楚为什么第二个参数具有uint8_t类型,同时您在 for 循环中使用int类型的变量。 . .

for (int i = 0; i < number_of_animals; i++)

If you want to return the index then the function should be declared like如果你想返回索引,那么 function 应该声明为

size_t SearchAnimalName( const Animal *animalName,  size_t number_of_animals)
{
    char search[10];
    scanf("%9s", search);

    size-t i = 0;

    while ( i < number_of_animals && strcmp(search, animalName[i].name) != 0 )
    {
        i++;
    }

    return i;
}

The function returns the index of the found element or the array size in case when the target element is not found. function 返回找到的元素的索引或数组大小,以防找不到目标元素。

To output the index you need to use the conversion specifier zu as for example对于 output 索引,您需要使用转换说明符zu作为示例

size_t i = SearchAnimalName( animalName, number_of_animals );

if ( i != number_of_animals ) printf( "i = %zu\n", i );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM