首页 > 解决方案 > How to search in a queue?

问题描述

Suppose if I enter 5 passenger's details I'm only able to retrieve the first passenger's details even if I search for the 4th passenger's details.I need to find any element in the list.If current= frontq; it's showing first element when searched.

CODE:

int search()
{   struct bag *next;

    char *n,*f;


    current=frontq;
    printf("Enter name to be searched:\n");
    scanf("%s",&n);
    printf("\nEnter the  flight number\n");
    scanf("%s",&f);
    while((current->name==n)&&(current->fl_no==f))
    {
    current=current->next;
    next++;
    }
     printf ("\n The Searched luggage is\n");
    printf("%s\n",current->name);
    printf("%s\n",current->dest);
    printf("%s\n",current->fl_no);
return 0;
    }

标签: csearchdata-structuresqueue

解决方案


对于初学者,这些指针

char *n,*f;

未初始化并且具有不确定的值。

而这些 scanf 的调用

scanf("%s",&n);
scanf("%s",&f);

使用不正确的参数并因此调用未定义的行为。

您需要声明适当大小的数组,例如

char n[N], f[N];

其中 N 是一些值,至少在 scanf 调用中写入

scanf( "%s", n);
scanf( "%s", f);

同样在写入错误比较指针的while循环的情况下

while((current->name==n)&&(current->fl_no==f))

你应该写

while( current != NULL && 
       !( strcmp( current->name, n ) == 0 && strcmp( current->fl_no, f ) == 0 ) )

在循环之后你应该写

if ( current != NULL )
{
    printf ("\n The Searched luggage is\n");
    printf("%s\n",current->name);
    printf("%s\n",current->dest);
    printf("%s\n",current->fl_no);
}

函数的返回值也没有意义。最好把返回表达式写成

return current != NULL;

在这种情况下,函数的用户可以检查是否找到了所需的队列元素。


推荐阅读