Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
开关箱在C中自动触发_C_File_Switch Statement_Infinite Loop - Fatal编程技术网

开关箱在C中自动触发

开关箱在C中自动触发,c,file,switch-statement,infinite-loop,C,File,Switch Statement,Infinite Loop,我有一个文件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.

我有一个文件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);
}

但是当我运行这个程序时,如果文件名与文件名匹配,它将进入一个无限循环,并无限地执行显示函数并触发搜索函数本身

如果没有使用正确的格式说明符正确地接收数据,就会发生这种情况

情况3
中,在
scanf
功能中,使用格式说明符

%s
而不是

%d

这将停止无限循环。

否,在插入函数中,我使用了fopen并以写入模式打开了文件,因此我关闭了该函数并重新打开。没关系,我在想其他事情。在案例3中,您没有正确读取学生姓名-您应该使用
%s
转换说明符,您不应该使用
&
运算符。您还应该检查
scanf
的结果-如果是0,则表示您没有成功读取任何内容,需要在重试之前清除输入流。清除流的一种简单方法是像
while(getchar()!='\n')这样的循环。是的,你是对的!格式说明符错误,谢谢!!!:)我不确定这是否值得回答,因为它已经被多次报道过了<代码>扫描频率(“%d”,选择(&C)仅读取十进制数字。当``scanf(“%d”,&choice)`下一次调用时,由于换行符,它立即终止,但仍将其留在缓冲区中。