我刚刚开始使用 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 语句(您需要说是/否)作为输出两次。 我知道发生这种情况是因为它将 Enter(即 '\n')视为另一个字符。 使用 fflush 没有帮助,因为它是一个无限循环。 我还能如何修改它以使最后一条语句仅显示一次?
最佳答案
您可以使用循环来使用 getchar()
读取剩下的任何字符:
ch=getchar();
int t;
while ( (t=getchar())!='\n' && t!=EOF );
ch
的类型应为 int
,因为 getchar()
返回 int
。您还应该检查 ch
是否为 EOF
。
fflush(stdin)
是根据 C 标准未定义的行为。虽然它是为某些平台/编译器(例如 Linux 和 MSVC)定义的,但您应该在任何可移植代码中避免使用它。
关于在无限 for 循环 C 程序中使用 getchar() 后,无法使用 fflush(stdin) 清除标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34246412/