//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);
}
实际上是这样:
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_sex(m / f),if语句的输出也没有实现。为什么呢?
答案 0 :(得分:6)
您正在针对未初始化的字符变量friend_sex
测试m
。您可能希望针对文字值'm'
进行测试。这就像有一个名为seven
的整数变量,并期望它保持值7
。
答案 1 :(得分:3)
char m, f
这声明了名为m和f的变量。这里m和f是变量名,而不是值'm'和'f'。现在他们正在包含垃圾值。
您需要初始化它们:
char m = 'm', f = 'f'
或者你可以将char常量直接放在if语句中,而不是使用变量m,f。
if (friend_sex == 'm') {}
答案 2 :(得分:1)
你检查了未初始化的friend_sex aginst m和f。你可以检查文字'm'或'f'
答案 3 :(得分:1)
您正在将friend_sex
与未初始化的变量m
进行比较。您应该将它与常量'm'
进行比较。请注意单引号。
答案 4 :(得分:1)
您需要检查if (friend_sex == 'm')
之类的内容,而不是根据变量m
进行检查。基本上你需要检查预期值。
答案 5 :(得分:1)
这是你的问题:
if(friend_sex == m)
您要比较两个变量,而不是您放入friend_sex
变量的内容。
所以如果你改成它:
if(friend_sex == 'm')
现在,这将检查friend_sex
的内容是否为'm'。