This question already has answers here:
How to compare char variables (c-strings)?
                                
                                    (5个答案)
                                
                        
                                7个月前关闭。
            
                    
我的代码无法正确比较if语句。当用户输入“ m”时,它将不会输出if主体中的内容

int main()
{
    char name[50];
    char gender[50];
    int num_gender=0; //calculate the characters in gender
    cout<<"Please input your name ";
    cin>>name;
cout<<"Gender ";
    cout<<" (m=male f=female) ";
    cin>>gender;
    num_gender=strlen(gender);
    if(num_gender!=1)
  {
    cout<<"Please enter m or f only";
  }
  if(gender=="m" || gender=="f")
    {
        if(gender=="m")
        {
          cout<<"hello Mr."<<name<<endl;
        }
        if( gender=="f" )
        cout<<"hello Ms."<<name<<endl;
    }


}

我希望输出将是您好先生或女士女士,后跟输入的名称,而不是什么

最佳答案

您可以使用string比较operator==对象。您不能以这种方式比较char*char[],因为它在数字上比较指针,而不是字符串本身。由于编译器将为"m""f"gender保留三个不同的内存位置,因此gender=="m"gender=="f"永远不会为真。

要将char*char[]作为字符串进行比较,请使用C函数strcmp

关于c++ - 当用户输入“m”时,为什么我的代码不能直接进入if主体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56421192/

10-11 22:08
查看更多