C++ If语句不起作用

pho*_*ton 1 c++ if-statement

//Writing a letter

#include <iostream>
using namespace std;

int main() {
string first_name;      //Name of addressee
string friend_name;     //Name of a friend top be mentioned in the letter
char friend_sex, m, f;  //variable for gender of friend

friend_sex = 0;

cout << "\nEnter the name of the person you want to write to: ";
cin >> first_name;

cout << "Enter the name of a friend: ";
cin >> friend_name;

cout << "Enter friend's sex(m/f): ";    //Enter m or f for friend
cin >> friend_sex;                      //Place m or f into friend_sex

cout << "\nDear " << first_name << ",\n\n"
     << "   How are you? I am fine. I miss you!blahhhhhhhhhhhhhhhh.\n"   
     << "blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.\n"
     << "Have you seen " << friend_name << " lately? ";

//braces only necessary if there are more than one statement in the if function
if(friend_sex == m) {
    cout << "If you see " << friend_name << ", please ask him to call me.";             
}   //If friend is male, output this
if(friend_sex == f) {
    cout << "If you see " << friend_name << ", please ask her to call me.";
}   //If friend is female, output this

return(0);
}
Run Code Online (Sandbox Code Playgroud)

这实际上是出来的:

Enter the name of the person you want to write to: MOM

Enter the name of a friend: DAD

Enter friend's sex(m/f): m

Dear MOM, 

        How are you? I am fine. I miss you! blahhhhhhhhhhhhhhhhh.
        blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.
        Have you seen DAD lately?
Run Code Online (Sandbox Code Playgroud)

这个程序正在模拟一个简短的字母.输出一个单词块很容易,但是当我想要一些条件放在字母中时,我遇到了麻烦.即使我在程序问我时输入了friend_sex(m/f),if语句的输出也没有实现.为什么?

Kat*_*ory 6

您正在测试friend_sex未初始化的字符变量m.您可能希望针对文字值进行测试'm'.这就像调用一个整数变量seven并期望它保存该值7.