2012-02-10 124 views
2
//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語句的輸出也沒有實現。爲什麼?

+0

您似乎沒有將「m」和「f」設置爲用於比較的任何值。 – 2012-02-10 20:40:09

+0

嘗試cout << friend_sex,看看它的設置。 – OnResolve 2012-02-10 20:41:23

+0

順便說一句,這是功課嗎?然後標記作業。 – taskinoor 2012-02-10 20:53:16

回答

6

您正在測試friend_sex針對未初始化的字符變量m。您可能想要根據字面值'm'進行測試。這就像有一個整數變量,稱爲seven,並期望它保存值7

1

您檢查了未初始化的friend_sex aginst m和f。您可以檢查字面'm'或'f'

1

您在比較friend_sex與未初始化的變量m。您應該將其與常數'm'進行比較。請注意單引號。

1

您需要檢查if (friend_sex == 'm')之類的內容,而不是根據變量m進行檢查。基本上你需要檢查預期的價值。

1

這是你的問題:

if(friend_sex == m) 

你比較兩個變量而不是你投入friend_sex變量的內容。

所以,如果你把它改成這樣:現在

if(friend_sex == 'm') 

,這將檢查內容的friend_sex是 'M'。

3

char m, f

這聲明瞭一個名爲M和F變量。這裏m和f是變量名,不是數值是'm'和'f'。現在他們包含垃圾值。

需要初始化它們:

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

或者你可以在if語句把字符常量,而不是直接使用變量M,F的。

if (friend_sex == 'm') {}