Nested conditional statements in C

I'm having a little trouble working with nested conditional statements in C.

int is_correct() { char YN ; printf( "Y or N : " ) ; scanf( "%c", &YN ) ; YN = toupper( YN ) ; return ( YN == 'Y' )? 1 : ( YN == 'N' )? 0 : is_correct() ; } 

I had the impression that the last line of code would return 1 or 0 if "Y" or "N" was entered, or call yourself again if an unexpected character was entered. Instead, it constantly calls itself regardless of input.

+4
source share
3 answers

Probably the scan is not working and you are not checking it.

You do not indicate that "continuously" means "not stopping to read more input", which, of course, should do.

Note, for example, that toupper() uses an int type argument and results, and expects values ​​of type unsigned char can get there undefined.

This is a really confusing aspect of ctype.h functions. I tend to use unsigned char in a call if the data comes from a text buffer ( char ).

Add a call to printf() to print the value of YN to the last line.

+2
source

The %c conversion does not read the newline character that you must enter after a one-character response.

In general, scanf() causes a lot more problems than it costs. Try using getline() to read a string from stdin to a string, and then use sscanf() to extract a character from a string.

Among other things, getline() allows you to specify the maximum input length, so you can easily avoid line buffer overflows.

+1
source

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() ; } 
0
source

Source: https://habr.com/ru/post/1488891/


All Articles