有没有办法建立性别评估

时间:2019-04-23 23:04:19

标签: c

我正试图让C程序的用户为男输入M,为女输入F 如果不符合M或F则循环遍历。 下面我尝试了以下代码,但是它循环两次给出正确的答案。 例如,输入M后,它将循环并打印

性别为假。.请输入M代表男性,M代表            女

有什么办法解决它。

目标是如果用户输入M或F,它将可以工作而无需再次输入。
如果有其他问题可能会多次询问

 #include "Gender.h"
 #include<stdio.h>


  char sex;
  void Gender(){

  printf("\nEnter Student Gender ('example M for Male  F for Female):\n");

  scanf(" %s",&sex);



      while (sex != "M" || sex != "M"){
       printf ("\n FALSE gender .. please enter M for Male and M for Female:\n");
        scanf(" %s",&sex);
        printf("\nStudent Sex :%c", sex,"\n");
        return;
      }


  }

2 个答案:

答案 0 :(得分:5)

sex是单个char变量,但是您将其视为指向字符串的指针。

  1. 将您的scanf调用更改为在格式字符串中使用%c(单个字符),而不是%s
  2. 将测试值sex的值更改为使用单引号(即if (sex == 'M'))。

请注意,如果将变量sex视为单个char,则此代码不需要进行字符串比较,如果将来要比较字符串项目,则不会使用运算符==!=-而是在<string.h>

中使用函数strcmp

答案 1 :(得分:1)

几件事,我提供了一个带有注释的实现...

包含ctype.h以使用toupper(3)并允许输入大写和小写字母。 您可以使用字符比较,也可以使用字符串比较,我给了你们两个,选择一个。

#include "Gender.h"
#include <stdio.h>

//you should really define these in your Gender.h file...
#define MALE "M"
#define FEMALE "F"
//you should really define these in your Gender.h file...
static const char* GenderAllowed = MALE" for Male and "FEMALE" for Female";
static const char* GenderPrompt = "Enter Student Gender";

//compare as string[1] - keep either this
#include <string.h>
int sexValidc( char* sex ) {
    return ( (0==strncmp(sex,MALE,1)) || (0==strncmp(sex,FEMALE,1)) );
}

//compare only first character - or keep this
#include <ctype.h>
int sexValids( char* sex ) {
    char sexch = toupper(*sex); //fold first character to upper case
    return ( (*MALE==sexch) || (*FEMALE==sexch) );
}

char Gender() {
    char sex[69+1]; //since you wanted to use %s, need a buffer, your &char allows stack overflow & wild memory pointer-ing
    printf("\n%s (%s):\n",GenderPrompt,GenderAllowed); //DRY - Dont Repeat Yourself...
    int done = 0;
    while( !done ) {
        scanf(" %69s",sex); //avoid stackoverflow :-)
        if( !sexValidc( sex ) ) {
//printf("blech, entered: %s\n",sex); //debugging, remove when comfortable
            printf("\n FALSE gender .. %s %s:\n",GenderPrompt,GenderAllowed);
        }
        else { //valid
            done = 1;
        }
    }
    printf("\nStudent Sex :%c\n", *sex);
    return *sex; //once you enter valid value, return it...
}

int main() {
    Gender();
}

还请阅读有关difference between %ms and %s scanf缓冲区空间自动分配的信息