我一直试图提出一种系统,该系统逐行搜索文件中的6位数字,当它找到它时,它将中断循环并输出找到的行,但是由于某种原因,每当我运行我的尝试时该程序刚刚退出。任何帮助,将不胜感激
searching = 1;
while (searching == 1) {
search = 0;
printf("Please enter the UP number of the student:\n");
scanf(" %d", &w);
while (search != 1) {
fgets(line, 60, StudentDB);
t = strstr(line, w);
if (t != NULL && t != -1) {
search = 1;
printf("The student's data is:\n");
printf("%s\n", line);
printf("What would you like to do now\n1. Edit marks\n2. Delete record\n3. Search for a different record\n4. Return to menu\n");
scanf(" %d", &v);
switch (v)
case 1:
case 2:
case 3:
break;
case 4:
;
break;
}
if (line == EOF) {
search = 1;
printf("There is no student with that UP number saved.\nWhat would you like to do?\n");
printf("1. Search for a different number\n2. Return to the menu\n");
scanf(" %d", &v);
switch (v) {
case 1:
break;
case 2:
searching = 0;
search = 1;
break;
}
} else {
printf("Something went horribly horribly wrong");
}
break;
}
}
您无法使用t = strstr(line, w);
搜索号码
strstr
的第二个参数必须是字符串。您应该将w
定义为char w [7];, read the 6 digit number as a string with
scanf(“%6s”,w)and use
strstr(line,w)`以在行中查找编号。
[还要注意,t != -1
毫无意义,t
应该是char *
,如果不存在该数字,则为NULL
;如果找到strstr
,则为指向该行的有效指针。] >
类似地,在搜索行之后测试文件末尾没有任何意义:在文件末尾,fgets()
返回NULL
并且未读取该行。