I have just started off with C programming and while I was trying to write a programme to accept only y or n characters I came across that
#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);
}
When I run this code, and type in any other character other than Y/y or N/n, I receive the last printf statement (You need to say either Yes/No) as output twice. I understand that this is happening because it considers enter, i.e, '\n' as another character. Using fflush doesn't help as it's an infinite loop. How else can I modify it so that the last statement is displayed only once?
You can use a loop to read any characters left using getchar()
:
ch=getchar();
int t;
while ( (t=getchar())!='\n' && t!=EOF );
The type of ch
should int
as getchar()
returns an int
. You should also check if ch
is EOF
.
fflush(stdin)
is undefined behaviour per C standard. Though, it's defined for certain platforms/compilers such as Linux and MSVC, you should avoid it in any portable code.