我一直在尝试设计一个系统,它可以逐行搜索文件中的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;
}
}发布于 2020-05-05 00:06:00
不能使用t = strstr(line, w);搜索号码
strstr的第二个参数必须是字符串。您应该将w定义为char w[7];,使用scanf("%6s", w)将6位数字作为字符串读取,并使用strstr(line, w)查找行中的数字。
还要注意,t != -1没有任何意义,t应该是一个char *,如果数字不存在,它将是NULL;如果strstr在行中找到数字,则将是指向该行的有效指针。
类似地,在搜索行之后测试文件的结尾也没有意义:在文件的末尾,fgets()返回NULL,并且该行没有被读取。
https://stackoverflow.com/questions/61596045
复制相似问题