微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C中char变量的问题

如何解决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;
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。