I was testing with c language today and I made two small c files
main.c
#include<conio.h>
void testing();
int main()
{
testing();
getch();
return 0;
}
testing.c
#include <stdio.h>
void testing()
{
char ch;
printf("Hello Testing\n");
do{
printf("Enter Character : ");
ch=getchar();
printf("You Entered : %c\n",ch);
testing();
}while(ch!='N');
}
The problem I am facing is it read one character from user and then it loop twice and I don’t know why
output
Hello Testing
Enter Character : k //(i entered k)
You Entered : k
Hello Testing// why this is displayed twice??
Enter Character : You Entered :// i don't press any key and it moves to next iteration
Hello Testing
Enter Character : // here i can enter character again and it happens again twice
I have complied it on Visual Studio 2012.
Because
getchar()leaves a newline character in the input buffer. You can use another getchar() to eat the newline.Or use scanf to eat leading whitespaces:
This way all the previous
\nwill be ignored.