2012-02-10 3 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」を設定していないようです。 –

+0

COUTを試してみてください<< friend_sex、それがに設定されていますかを参照してください。 – OnResolve

+0

ところで、これは宿題ですか?その後、宿題にタグを付けます。 – taskinoor

答えて

6

あなたは初期化されていない文字変数mに対してfriend_sexをテストしています。リテラル値'm'に対してテストすることをお勧めします。それはsevenと呼ばれる整数変数を持つと、それは価値7を保持するために期待するようなものです。

1

あなたが初期化されていないMとF aginst friend_sex確認してください。リテラル 'm'または 'f'と照合することができます

1

friend_sexと初期化されていない変数mを比較しています。それを定数'm'と比較する必要があります。一重引用符に注意してください。

1

あなたは、変数mに対してそれをチェックするのではなく、if (friend_sex == 'm')のようなものをチェックしたいと思います。基本的には、期待値と照合する必要があります。

1

これはあなたの問題である:

if(friend_sex == m) 

次の2つの変数はなく、あなたがfriend_sex変数に入れた内容を比較しています。

は、だから、このように変更した場合:

if(friend_sex == 'm') 

さて、これはfriend_sexのが 'M' であるコンテンツかどうかをチェックします。

3

char m, f

これはMとFという名前の変数を宣言します。ここで、mとfは変数名であり、値は 'm'と 'f'ではありません。今はゴミ値を含んでいます。

あなたはそれらを初期化する必要があります。

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

それとも、代わりに変数m、Fを使用してのif文で直接文字定数を置くことができます。

if (friend_sex == 'm') {}