C++ 如果语句不起作用

C++ If statement won't function

本文关键字:不起作用 语句 如果 C++      更新时间:2023-10-16
//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 << ",nn"
     << "   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);
}

这是实际结果:

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?

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

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

char m, f

这将声明名为 m 和 f 的变量。这里的 m 和 f 是变量名,而不是值是 'm' 和 'f'。现在它们包含垃圾值。

您需要初始化它们:

char m = 'm', f = 'f'

或者你可以直接在 if 语句中放置 char 常量,而不是使用变量 m、f。

if (friend_sex == 'm') {}

你检查friend_没有初始化的 aginst m 和 f。 您可以检查文字"m"或"f">

您需要检查类似if (friend_sex == 'm')的内容,而不是根据变量m进行检查。基本上,您需要检查预期值。

这是您的问题:

if(friend_sex == m)

正在比较两个变量,而不是您放入friend_sex变量的内容。

因此,如果您将其更改为以下内容:

if(friend_sex == 'm')

现在,这将检查friend_sex的内容是否为"m"。

您正在将friend_sex与未初始化的变量进行比较,m 。 您应该将其与常量'm'进行比较。 请注意单引号。