简体   繁体   English

在C编程中遇到麻烦if else语句

[英]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. 当我键入M或F时,它会直接跳到循环的“无效选项”部分,而不是打印特定的文本。 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 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. 您可能要使用getchar或类似的东西代替scanf,或对%s使用%c。 Right now, it seems like you're asking for an int, but checking for a character input. 现在,似乎您要输入一个int,但要检查一个字符输入。

The %d format specifier scans for a base-10 integer. %d格式说明符扫描以10为底的整数。 You are asking for a char . 您要一个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" . char的正确格式说明符是%c ,而避免scanf找不到有效输入并将其留在stdin可避免死循环的正确格式字符串" %c" That is, if you insist on using scanf , instead of getchar or fgets . 也就是说,如果您坚持使用scanf ,而不是getcharfgets

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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