-3

我正在根据我的教科书进行练习,并且一直遇到问题。这是代码。

#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 语句与用户输入的字符一起工作。即使我输入 f,它也总是运行男性语句。

4

4 回答 4

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?";
}
于 2013-05-04T20:02:58.670 回答
1

第一个运行,因为您设置friendsex为“m”。friendsex = 'm'应该是friendsex == 'm'。'f' 也一样。

于 2013-05-04T20:05:03.147 回答
0

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

于 2013-05-04T21:12:48.297 回答
-1

使用 == 而不是 = 不要使用 'm; 因为我相信您正在尝试使用局部变量。

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

于 2013-05-04T20:06:10.087 回答