C++ 如果语句不使用用户输入的字符=字符

C++ 如果语句不使用用户输入的字符=字符,c++,C++,我在做课本上的一个练习,但一直有问题。这是代码 #include <iostream> using namespace std; int main(){ string name; string friend_name; char friendsex; char m = 'm'; char f = 'f'; cout << "Enter the name of the person you would like to write to" << endl; c

我在做课本上的一个练习,但一直有问题。这是代码

#include <iostream>
using namespace std;

int main(){
string name;
string friend_name;
char friendsex;
char m = 'm';
char f = 'f';

cout << "Enter the name of the person you would like to write to" << endl;
cin >> name;
cout << endl << "Dear " << name <<", " 
    << endl 
    << endl 
    << "Hey how are you? I myself have been fine recently. I've been wanting to do some catching up with you"
    << endl
    << endl
    << "Please enter the name of a friend now"
    << endl;
cin >> friend_name;  
cout << endl << "Hey how are you? I myself have been fine recently. I've been wanting to do some catching up with you. Have you seen " << friend_name << " recently?" << endl << endl;
cout << "Please enter the sex of your friend (m/f)"
    <<endl;
cin >> friendsex;

if(friendsex = 'm'){
    cout << "If you have, could you please tell him to call me?";
}
else if(friendsex = 'f'){
    cout << "If you have, could you please tell her to call me?";
}
return 0;
}
#包括
使用名称空间std;
int main(){
字符串名;
字符串friend\u name;
性别;
charm='m';
字符f='f';
姓名;

CUT< P>使用<代码> ==< /> >而不是<代码> > <代码> >代码>=/COD>将右手分配给左边,然后评估新值。在C++中,除0以外的任何值都将被评估为<代码>真< /COD>,因此您的第一个if语句总是执行。< /P>
if(friendsex == 'm'){
    cout << "If you have, could you please tell him to call me?";
}
else if(friendsex == 'f'){
    cout << "If you have, could you please tell her to call me?";
}
if(friendsex='m'){

因为您将
friendsex
设置为'm',
friendsex='m'
应该是
friendsex='m'
。与'f'相同。

使用==代替= 不要使用'm;,因为我相信您正在尝试使用局部变量

如果(friendsex==m){ ............. } else if(friendsex==f){ .................
}

如果不能使用赋值运算符“=”执行语句。
使用“==”用于比较

打开编译器警告。它们可以帮助您并节省人们回答编译器可以回答的问题的时间,以及调试和最终提问所需的时间。
char friendsex
很有趣……它们打开了。脚本运行时我没有收到错误。但是第二个if语句无法运行no m根据我输入的内容。@user2349335,确保您至少使用了
-Wall
。GCC给出了以下提示:警告:建议在用作真值[-wParenthes]的赋值周围加括号我很确定Clang's就像简单的英语。为什么要发布与nullptrs相同的答案?因为我的页面没有刷新,也没有显示他的答案;)足够公平,然后你会得到一个+1:-)我想我本来就有这样的答案,但当我遇到编译器无法识别字符m和f的问题时,我会更改它们,因为它们没有声明,所以我改为=代替,不知道我在做什么。noob搞错了。在我为m和f添加了字符声明并将其改为==之后,它运行正常。谢谢!@user2349335,如果你用
friendsex==m
代替
friendsex='m'
,它只会抱怨。后者是一个文本,不需要声明。@chris He之前在程序中定义了
m
f
好的。不知道添加“”可以做到这一点。感谢您提供的信息!@nullptr,从我收集的信息来看,他直到尝试了
friendsex==m
之后才这么做。您能添加一些关于为什么有人应该使用此功能的信息吗?键入
您真的有那么困难吗de>,
,和
?对于Max-如果您查看与此问题一起发布的代码………char m='m';char f='f';…因此编码人员实际上正在尝试/计划使用变量m和f,使用变量比使用硬编码字符串fp进行比较总是更好…如果明天需求发生变化m=“Male”和f=“Female”…那么只需要在代码的最顶端进行更改…简言之,它的编码标准。。