【问题标题】:Trouble with char variable in CC中char变量的问题
【发布时间】:2021-04-11 02:09:03
【问题描述】:

为什么这个代码不接受我设置它接受的字母?它应该接受 M、F、m 和 f,但它没有我缺少什么?太棒了

#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';
}

【问题讨论】:

  • 您的意思是&amp;&amp; 而不是||??而且...scanf (" %c", &amp;sexo) 可以。格式字符串中不需要额外的尾随' '
  • 例如的反面sexo == 'M' || sexo == 'F'sexo != 'M' &amp;&amp; sexo != 'F'。我建议你阅读De Morgan's laws

标签: c char


【解决方案1】:

我对你的代码做了一些修改,并在 cmets 中添加了一些解释。

#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 的一个问题(除了它可能不安全)是很难处理错误和输入问题,正如您在 cmets 中评论的那样到这个答案。在这里可以做不同的更好的事情。其中一个更简单的是使用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;
        }
    }
}

【讨论】:

  • 您好,欢迎回复!我试过了,显然代码块给我返回了这个:“E:\Codeblocks\Projetos\TESTE.c|7|error: 'true' undeclared (first use in this function)|”
  • 但是,如果我将 true 替换为:"sexo!='M'&&sexo!='F'&&sexo!='m'&&sexo!='f'" 它将完美运行!
  • 就像在我的代码中一样,如果我输入一个不同于 M 或 F 的字符,它会返回两次“Sexo invalido!Precisa ser 'M' ou 'F'”
  • 好的。第一个是 C++“错误”。您可以将true 替换为 1。您收到的多条消息是因为 scanf 从流中读取的。例如,如果您输入 DDDDDF,您将收到 4 条无效性别的消息,然后程序结束,返回 F。当您输入 G 时,您的输入流实际上包含两个字符(G 和 \n)。 \n 在第二次运行中被读取,因此您收到两条消息。您可以通过在 scanf 语句之后添加 printf("%d\n", sexo); 来看到这一点。您不应该使用 scanf()。试试别的,比如gets()。我添加了对帮助的答案的编辑。
猜你喜欢
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 2022-01-22
  • 2011-07-04
  • 2021-10-25
  • 1970-01-01
相关资源
最近更新 更多