简体   繁体   中英

Having trouble with a C programming if else statement

When I type an M or an F, it skips straight to the "Invalid Option" part of the loop instead of printing the specific text. Any input is appreciated.

    #include <stdio.h>
    int main() {

      int MorF; //gender choice

       printf("_____________________________________\n\n"); 
       printf("Pick a gender. Type: M for Male or F for Female\n");
       scanf(" %d" , &MorF);
        if ( MorF == 'm' || MorF == 'M' ) { 
           printf("You chose Male\n");
       } else if ( MorF == 'f' || MorF == 'F' ) {
           printf("You chose Female\n");
       } else {
        printf("Invalid Option\n");  
}
printf("______________________________________\n\n");

}

https://www.tutorialspoint.com/c_standard_library/c_function_getchar.htm

You might want to use getchar or something similar instead of scanf, or use %c for scanf. Right now, it seems like you're asking for an int, but checking for a character input.

The %d format specifier scans for a base-10 integer. You are asking for a char . The correct format specifier for char is %c , and the correct format string to avoid an infinite loop because scanf didn't find valid input, and left it in stdin , is " %c" . That is, if you insist on using scanf , instead of getchar or fgets .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM