程序运行良好,直到我创建文件并从结构中输入记录,但是当我尝试使用 roll no 搜索记录时,它崩溃了。
我使用一个名为 student 的结构来存储数据,然后创建一个文本文件,然后使用 for 循环将数据写入文本文件。然后我重新打开文件并尝试使用学生名册号搜索记录。
程序运行良好,直到我尝试搜索学生名册号。输入要搜索的学生名册后立即崩溃。
谁能告诉我需要进行哪些修改才能使搜索工作?
下面是我的代码:
#include<stdio.h>
struct student {
int roll_no;
char name [80];
int age;
}st[30],s;
int main ()
{
int i,n;
char fname[80];
int search;
int found;
FILE *fp;
printf("\nEnter the file name : \n");
scanf("%s",fname);
fp=fopen(fname,"w");
if(fp==NULL)
{
printf("\nCannot create file :");
exit(0);
}
printf("\nNumber of students : \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nInformation for student#%d : \n\n",i+1);
printf("\nStudent roll number : \n" );
scanf("%d",&st[i].roll_no);
printf("\nStudent name: \n: ");
scanf("%s",st[i].name);
printf("\nStudent age : ");
scanf("%d", &st[i].age);
}
fprintf(fp, "\nStudent roll no\t\t Student name\t\t student age\t\t\n\n");
for(i=0;i<n;i++)
{
fprintf(fp, "\n%d \t\t %s \t\t %d \t\t", st[i].roll_no,st[i].name,st[i].age);
}
fclose(fp);
fp=fopen(fname,"r+t");
if(fp==NULL)
{
printf("\nCannot open file\n");
exit(0);
}
printf("\n\nStudent roll no to be searched : ");
found=0;
scanf("%d", search);
while(!(feof(fp)) && (found==0))
{
fscanf(fp,"%d,%s,%d",&s.roll_no,s.name,&s.age);
if(s.roll_no==search)
{
fseek(fp,-sizeof(struct student), SEEK_CUR);
printf("\nEnter new name : \n");
scanf("%s", s.name);
fprintf(fp, "\n%d \t\t %s \t\t %d \t\t", s.roll_no,s.name,s.age);
found=1;
}
}
if(found=0)
{
printf("\nStudent record doesn't exist \n");
}
fclose(fp);
return 0;
}
最佳答案
在您的代码中,您在 scanf()
中缺少一个address-of 运算符,从而传递了一个无效类型的参数。基本上
scanf("%d", search);
应该是
scanf("%d", &search);
也就是说,限制字符串输入的大小始终是一个好习惯,例如,对于定义为 char fname[80];
的数组,您应该使用
scanf("%79s",fname);
避免过长的输入可能造成的缓冲区溢出。
此外,始终检查 scanf()
和函数系列的返回值以确保它们成功。
关于c - 以下代码有什么问题?我正在尝试在文本文件中搜索记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33607395/