我刚开始使用 C 编程,当我试图编写一个只接受 y 或 n 个字符的程序时,我遇到了
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Do you want to continue\n");
for (;;)
{
ch=getchar();
if (ch=='Y' || ch=='y')
{
printf("Sure!\n");
break;
}
else if (ch=='N'||ch=='n')
{
printf("Alright! All the best!\n");
break;
}
else
{
printf("You need to say either Yes/No\n");
fflush(stdin);
}
}
return(0);
}
当我运行此代码并输入除 Y/y 或 N/n 之外的任何其他字符时,我会收到最后一个 printf 语句(您需要说是/否)作为输出两次。我知道发生这种情况是因为它认为输入,即 '\n' 作为另一个字符。使用 fflush 无济于事,因为它是一个无限循环。我还能如何修改它以使最后一条语句只显示一次?