0

My program is supposed to display the name of the requested shape. I'm not used to working with strings, so how would I echo the users input ( C displays cone, etc.)? I'm guessing an if statement of some sort, but not sure how to write it.

Sample:

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!

Code:

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;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

1

The statement

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

means

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

because the comma operator has lowest precedence of all operators.

So it inputs one character, into C, and then (this is what the comma operator does) evaluates U, Y, P, S and Q, with the latter's value as the expression result, which is then discarded.

That's probably not what you thought it did.

To make this work you can

  • Use a single input variable, say, called line.

  • Use the getline function from the <string> header to input one line.

  • Check whether that line of input is "U", in which case do the U thing, or some other letter, in which case do other things. The if statement is good for this.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
1

This code is wrong.

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

That will try to write whatever the user types into the memory that C points to. The other comma separated parts are individual statements that have no effect.

What you want to do is write the user's input to a new variable.

char choice;
cin >> choice;

Then look at what that is and respond accordingly.

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

etc.

Jason
  • 1,612
  • 16
  • 23