Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.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中的Do…While和getche()_C - Fatal编程技术网

C中的Do…While和getche()

C中的Do…While和getche(),c,C,在我的程序中的以下代码中: do { printf("\nEnter records of student %d: \n", i++); printf("Name: "); fgets(record.name, sizeof(record.name), stdin); printf("\nAddress: "); fgets(record.addre

在我的程序中的以下代码中:

do
    {
        printf("\nEnter records of student %d: \n", i++);
        printf("Name: ");
        fgets(record.name, sizeof(record.name), stdin);
        printf("\nAddress: ");
        fgets(record.address, sizeof(record.address), stdin);
        printf("\nClass Level: ");
        scanf("%d", &record.classlevel);
        printf("\nTelephone Number: ");
        scanf("%ld",&record.telephone);
        fwrite(&record, sizeof(record),1,fptr);
        printf("\n\nAdd another record? [y/n]: ");


    }while(getche()=='y');
当我看到输出时,它第一次运行良好

输入学生1的记录

姓名:

地址:

班级级别:

电话号码:

添加另一个记录?[是/否]:

输入学生2的记录

名称:<没有光标出现,无法在此提供输入>

地址:

。。。。。等等

发生了什么,为什么我不能在do…while循环的第一次迭代后输入名称。getche()有什么问题吗

希望你的帮助


提前感谢

你需要在你的
do{…}开始时
fflush(stdin)
因为
getche()
在输入缓冲区中留下一个换行。

你需要在
do{…}开始时
fflush(stdin)
因为
getche()
在输入缓冲区中留下一个换行符。

这已经讨论了无数次了。基本上,scanf在缓冲区中留下换行符,作为输入传递给下一个调用。每次调用scanf后,都需要清除(刷新)输入缓冲区。这已经讨论了无数次了。基本上,scanf在缓冲区中留下换行符,作为输入传递给下一个调用。每次调用scanf后,都需要清除(刷新)输入缓冲区<代码>fflush(stdin)
是未定义的行为。一些实现声称,
fflush
ing输入流实现了预期的功能,但我不建议在那里这样做。你是对的,但我确实记得用这种方式解决了类似的问题。是的,它可能会起作用,但我宁愿不依赖它。我的手册页上写着“对于输入流,
fflush()
丢弃从底层文件中提取的、但应用程序尚未使用的任何缓冲数据”。但如果我没有记错的话,我在
stdin
上试过一次,但没有成功。那么,你还有什么建议@danielfisher?(不过这一次起作用了)@cipher通常是旧的
intch;而((ch=getchar())!=EOF&&ch!='\n');如果(ch==EOF){/*输入错误,stdin关闭或损坏,如何处理?*/}
循环就足够了。如果您可能需要从缓冲区中读取多行数据,则会出现问题。
fflush(stdin)
是未定义的行为。一些实现声称,
fflush
ing输入流实现了预期的功能,但我不建议在那里这样做。你是对的,但我确实记得用这种方式解决了类似的问题。是的,它可能会起作用,但我宁愿不依赖它。我的手册页上写着“对于输入流,
fflush()
丢弃从底层文件中提取的、但应用程序尚未使用的任何缓冲数据”。但如果我没有记错的话,我在
stdin
上试过一次,但没有成功。那么,你还有什么建议@danielfisher?(不过这一次起作用了)@cipher通常是旧的
intch;而((ch=getchar())!=EOF&&ch!='\n');如果(ch==EOF){/*输入错误,stdin关闭或损坏,如何处理?*/}
循环就足够了。如果您可能需要从缓冲区中读取多行,那么它会变得很麻烦。