In scanf("%c",&YN) put a space before the %c conversion specifier as scanf(" %c",&YN) to eat the newline character ( \n )
#include <stdio.h> #include <ctype.h> int is_correct(void) { char YN ; printf( "Y or N : " ) ; scanf(" %c",&YN); YN = toupper( YN ); return YN == 'Y' ? 1 : YN == 'N' ? 0 : is_correct() ; } int main() { printf("%d",is_correct()); return 0; }
I tested it. Works fine if you only type one character (excluding \n )!
In a more efficient way, you can do this; store the first character in char ch , and then use the while((YN = getchar()) != '\n') to eat all the other characters, including \n . Example: If you type ynabcd , the first character y will be stored in ch as y , and rest will depend on the while( .
int is_correct(void) { char YN ; printf( "Y or N : " ) ; scanf("%c",&YN); char ch = toupper( YN ); while((YN = getchar()) != '\n') ; return ch == 'Y' ? 1 : ch == 'N' ? 0 : is_correct() ; }
source share