0

私のプログラムは、要求された形状の名前を表示することになっています。文字列の操作に慣れていないので、ユーザー入力をどのようにエコーしますか (C はコーンなどを表示します)。ある種のif文を推測していますが、その書き方がわかりません。

サンプル:

Hello.  Welcome to the shape volume  computing program.
Which shape do  you have?  (C for cone, U for   cube,   Y, for  cylinder P for pyramid, S   for sphere, or Q    to quit)
Enter   shape:  U
okay,   cube.   Please enter the length of a side:  3
okay,   the length of the side = 3
the volume  = 27
enter   shape: C
okay,   cone.   Please enter the radius of the  base:   2
please enter the height:    3
okay,   the radius =  2 and the height  = 3
the volume  = 12.56
enter   shape: Q
bye!

コード:

int main()
{
    string C,U,Y,P,S;
    C= "cone";
    U= "cube";
    Y= "cylinder";
    P= "pyramid";
    S= "sphere";
    int Q= -1;

    cout<< " Enter C for cone, U for cube, Y for cylinder, P for pyramid, S for sphere or Q
    to quit. " <<endl;
    cin>> C,U,Y,P,S,Q;

    if(Q= -1)
        cout<< " Goodbye! " <<endl;
    return 0;
}
4

2 に答える 2

1

ステートメント

cin>> C,U,Y,P,S,Q;

意味

(cin>> C),U,Y,P,S,Q;

コンマ演算子はすべての演算子の中で最も優先度が低いためです。

したがって、1 つの文字を に入力しC、(これはカンマ演算子が行うことです) UYPSおよび を評価Qし、後者の値を式の結果として破棄します。

それはおそらくあなたが思っていたことではありません。

これを機能させるには、次のことができます

  • という名前の単一の入力変数を使用しますline

  • ヘッダーからgetline関数を使用して1 行を入力します。<string>

  • その入力行が であるかどうかを確認します"U"。この場合は U のことを行い、他の文字の場合は他のことを行います。ステートメントはこれifに適しています。

于 2012-10-26T02:42:05.477 に答える
1

このコードは間違っています。

cin >>  C,U,Y,P,S,Q;

これは、ユーザーが入力したものを C が指すメモリに書き込もうとします。カンマで区切られたその他の部分は、効果のない個々のステートメントです。

やりたいことは、ユーザーの入力を新しい変数に書き込むことです。

char choice;
cin >> choice;

次に、それが何であるかを見て、それに応じて応答します。

if ('C' == choice)
{
   // print output
}
else if ('U' == choice)
{
   // print output

于 2012-10-26T02:42:33.290 に答える