Switch Case 在 C 中被自己触发

Switch Case is getting triggered by itself in C

我有一个文件student.txt,它的内容类似于

Name RollNo Address ...\n
Name RollNo Address ...\n

而且我写了一个函数来搜索文件中的名称 它是菜单驱动的,就像

 std student;
 FILE *file = NULL;
 int choice;
 char name[20];
 while (1)
    {
        printf("Enter the choice\n1.Insert\t2.Append\t3.Search\t4.Display: ");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            //insertion
            break;
        case 2:
            // append 
            break;
        case 3:
            printf("Enter the student name to be searched: ");
            scanf("%d", &name);
            search(name, &file);
            break;
        case 4:
            // display
            break;
        default:
            exit(0);
            break;
        }
    }
    return 0;

搜索功能是

void search(char ele[], FILE **fileptr)
{
    *fileptr = freopen("student.txt", "r", *fileptr);
    char line[100];
    while (fgets(line, 100, *fileptr) != NULL)
    {
        if (strstr(line, ele) != NULL)
        {
            getchar();
            printf("Congrats !!\n");
            return;
        }
    }
    printf("not found\n");
    fclose(*fileptr);
}

但是当我 运行 虽然文件名与文件名匹配时,它会进入无限循环并执行显示功能并无限触发搜索功能本身

当没有使用正确的格式说明符正确获取数据时,就会发生这种情况。

case 3中,在scanf函数中,使用格式说明符

%s

而不是

%d

这将停止无限循环。