//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);
}
這是實際出來:C++如果語句不會起作用
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語句的輸出也沒有實現。爲什麼?
您似乎沒有將「m」和「f」設置爲用於比較的任何值。 – 2012-02-10 20:40:09
嘗試cout << friend_sex,看看它的設置。 – OnResolve 2012-02-10 20:41:23
順便說一句,這是功課嗎?然後標記作業。 – taskinoor 2012-02-10 20:53:16