C中char变量的问题

问题描述

为什么这个代码不接受我设置为接受的字母?它应该接受 M、F、m 和 f,但它不是我错过了什么? ty

#include<stdio.h>

int main(){
    char sexo;
    sexo='A';
    printf("== Entre com o sexo:\n");
    while(sexo!='M'||sexo!='F'||sexo!='m'||sexo!='f'){
        scanf(" %c ",&sexo);
        if(sexo!='M'||sexo!='F'||sexo!='m'||sexo!='f'){
            printf("Sexo invalido!Precisa ser 'M' ou 'F'.\n");
        }
        else{
            return sexo;
        }
    }
    sexo='A';
}

解决方法

我对您的代码进行了一些修改,并在注释中添加了一些说明。

#include <stdio.h>
#include <ctype.h>

int main() {
    char sexo = 'A';
    printf("== Entre com o sexo:\n");
    while(1) {  // No need to test everything twice. This loop will go until we hit the return inside it.
        scanf("%c",&sexo); // Removed spaces in the formatting string
        sexo = toupper(sexo); // Will make everything uppercase,making the next test simpler.
        if(sexo!='M' && sexo!='F') { // Changed to && - this is true if it is neither M nor F
            printf("Sexo invalido! Precisa ser 'M' ou 'F'.\n");
        }
        else{
            return sexo; // Return here,otherwise keep going. Unlike the original,this will return only M or F,and never m or f
        }
    }
}

编辑: scanf 的一个问题(除了它可能不安全的事实之外)是很难处理错误和输入问题,正如您在评论中所评论的那样到这个答案。在这里可以做不同的更好的事情。一个更简单的方法是使用 fgets,读取整行,然后使用第一个字符,忽略其余字符(或者您可以添加额外的错误处理)。像这样:

#include <stdio.h>
#include <ctype.h>

#define MAX 20

int main() {
    printf("== Entre com o sexo:\n");
    while(1) {  // No need to test everything twice. This loop will go until we hit the return inside it.
        char buf[MAX];
        fgets(buf,MAX,stdin);
        char sexo = toupper(buf[0]);
        if(sexo!='M' && sexo!='F') {
            printf("Sexo invalido! Precisa ser 'M' ou 'F'.\n");
        }
        else{
            return sexo;
        }
    }
}