如果语句不能与用户输入char = char

时间:2013-05-04 20:00:51

标签: 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;
}

我无法弄清楚如何使if语句与用户输入的char一起使用。即使我输入f,它也总是运行男性陈述。

4 个答案:

答案 0 :(得分:4)

使用==而不是==将右侧分配给左侧,然后评估新值。在C ++中,除0之外的任何值都将计算为true,因此您的第一个if语句将始终执行。

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?";
}

答案 1 :(得分:1)

第一个运行是因为您将friendsex设置为'm'。 friendsex = 'm'应为friendsex == 'm'。 'f'相同。

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

使用==而不是= 不要用'm;因为我相信你正试图使用​​局部变量。

if(friendsex == m){     ............. } 否则if(friendsex == f){    ................. }