使用 strstr 逐行搜索

Line by line searching using strstr

我一直在尝试想出一个系统,逐行搜索文件中的 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];,使用 scanf("%6s", w) 将 6 位数字读取为字符串,然后使用 strstr(line, w) 查找行中的数字。

另请注意,t != -1 没有意义,t 应该是 char *,如果数字不存在或有效指针,它将是 NULL如果 strstr 找到上面的号码,则进入该行。

同样,在搜索行后测试文件末尾是没有意义的:在文件末尾,fgets() returns NULL 并且未读取该行。