m0_52594097 2021-06-30 22:21 采纳率: 50%
浏览 43
已采纳

C语言,查找功能怎么写?

求问如何改善查找功能达到输入姓名一部分,前部分后部分都可以找到有关的信息,而不相关的信息不会输出 以下是部分代码:

    int is_find=0;
    char find[NUM];
    //记录需要查找的内容,并作为查找成功与否的标识符
    printf("Please enter the name you want to find:");
    getchar();
    gets(find);
    for(int i=0;i<NUM;i++)
    {
        if(strcmp(stu[i].name,find)>=0)
        {
            printf("\nSearch success\n");
            printf("The student's student number is:%s\n",stu[i].id);
            printf("The student's name is:");
            printf("%s",stu[i].name);
            printf("\nThe student's scores in various subjects are\n");
            for(int c=0;c<3;c++)
            {
                printf("The result of the %d course is %.2f\n",c+1,stu[i].ach[c]);
            }
            printf("The student's total score is:%.2f",stu[i].sum);
            printf("\n");
            is_find=1;
        }
    }
    if(is_find!=1)
    {
        printf("There is no such person\n");
    }
    getch();
  • 写回答

2条回答 默认 最新

  • qfl_sdu 2021-06-30 22:55
    关注

    定义一个字符串查找函数,然后再if中调用就可以了,如下:

    //判断字符串s是否包含字符串t
    int isContain(char* s,char* t)
    {
        char*p,*q;
        while(*s)
        {
            p = s;
            q = t;
            while(*q)
            {
                if(*p != *q)
                    break;
                q++;
                p++;
            }
            if(*q=='\0')
                return 1;
            s++;
        }
        return 0;
    }
    
    
    //然后将if(strcmp(stu[i].name,find)>=0),这句话改成:if(isContain(stu[i].name,find))
    //下面是修改后的代码:
    int is_find=0;
        char find[NUM];
        //记录需要查找的内容,并作为查找成功与否的标识符
        printf("Please enter the name you want to find:");
        getchar();
        gets(find);
        for(int i=0;i<NUM;i++)
        {
            if(isContain(stu[i].name,find))
            {
                printf("\nSearch success\n");
                printf("The student's student number is:%s\n",stu[i].id);
                printf("The student's name is:");
                printf("%s",stu[i].name);
                printf("\nThe student's scores in various subjects are\n");
                for(int c=0;c<3;c++)
                {
                    printf("The result of the %d course is %.2f\n",c+1,stu[i].ach[c]);
                }
                printf("The student's total score is:%.2f",stu[i].sum);
                printf("\n");
                is_find=1;
            }
        }
        if(is_find!=1)
        {
            printf("There is no such person\n");
        }
        getch();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题