使用C编程在文件中搜索字符串 [英] Search String in File Using C programming

查看:72
本文介绍了使用C编程在文件中搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C语言创建学生信息系统。

结构是

I am creating Student Information system in C language.
the Structure is

struct { char firstname[20];
char pass[20];
}student;







打印文件中的字符串格式低于




Print the String in File with Below Format

fprintf(fp,"%d\t\t%s\t\t P\t\t%d:%d:%d\t\t\n",index,student.firstname,t.ti_hour,t.ti_min,t.ti_sec);







<pre lang="cs">void searchname()
{  int index;
found=0;
fp=fopen("attdb.txt","r");
if(fp == NULL)
    {
     outtextxy(100,450,"! The File is Empty...\n\n");
     }
      else
    {
    outtextxy(100,300,"\nEnter student first name:");
     scanf("%s",&studentname);
    do
    {      
    fscanf(fp,"%d\t\t%s",index,student.firstname);
    length = strlen(student.firstname);
    if(student.firstname[length]==studentname[length])
    found=1;
    }while(!feof(fp));
}
 if(found==1)
 {
    outtextxy(100,400,"\nThe record is found.");
    getch();
  }
 else
 {
     outtextxy(100,400,";Not found...\n");

 }







它在无限循环中消失...




its is gone in infinite loop...

推荐答案

   if(student.firstname[length]==studentname[length])
    found=1;
    }while(!feof(fp));
}



这不起作用,您需要使用正确的字符串比较函数来检查名称是否匹配。扫描字符串输入字段时,你也不需要&符号& 在变量名上。


我会改变



I would change

do
{
fscanf(fp,"%d\t\t%s",index,student.firstname);
length = strlen(student.firstname);
if(student.firstname[length]==studentname[length])
found=1;
}while(!feof(fp));





to





to

while !feof(fp)
{
    fscanf(fp,"%d\t\t%s",index,student.firstname);
    length = strlen(student.firstname);
    if(student.firstname[length]==studentname[length])
        break;
}


您可能想要包含 ||在你的while循环条件下找到!= 1



祝你好运!
You might want to include || found != 1 in your while loop condition.

Good luck!


这篇关于使用C编程在文件中搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆