0

Here is the code, my output, with expected output below.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class geometricShape
{
protected:
const double pi = acos(-1);
string userInputHeight = "";
string userInputRadius = "";
double height = 0;
double radius = 0;
public:
void setValues()
{
        while (true)
        {
        cout << "Please input the height: " << endl;
        getline(cin, userInputHeight);
        stringstream heightStream(userInputHeight);
        cout << "Please input the radius:" << endl;
        getline(cin, userInputRadius);
        stringstream radiusStream(userInputRadius);
        height = atof(userInputHeight.c_str());
        radius = atof(userInputRadius.c_str());
        if (heightStream >> height && radiusStream >> radius && height > 0 && radius > 0)
            {
            break;
        }
        cout << "Invalid input, please try again." << endl;
    }
 }
};
class cylinder : public geometricShape
{
public:
double volume()
{
    double radiusSquared = radius * radius;
    double cylinderVolume = pi*radiusSquared*height;
    return cylinderVolume;
}
};
int main(void)
{
int userInput = 0;
cout << "Please choose a volume to calculate: " << endl;
cout << "1. Cyliner." << endl;
cout << "2. Cone." << endl;
cin >> userInput;

switch (userInput)
{
case 1:
{
          //call right circular cylinder function
          cylinder cylndr;
          cylndr.setValues();
          cout << cylndr.volume() << endl;

          break;
}
case 2:
{
          cout << "case 2";
          break;
}
default:
{
           cout << "Invalid selection, please choose again." << endl;
}

}


cin.get();

}

What I expect to happen when I press 1 for Cylinder, is for it to ask me to "Please input the height:" and then wait for a response, then ask for the radius input.

What is actually happening is that it's printing out both messages immediately, and then telling me my input is incorrect, and then runs correctly the 2nd time.

trueCamelType
  • 2,198
  • 5
  • 39
  • 76

2 Answers2

2

When your cin>>userInput executes, it only reads the integer from the stream and leaves the newline character (when you press enter) in the stream. Your getline function reads till it finds the end of a line, which is already present on the cin stream so your userInputHeight is read and contains an empty line.

So you can fix your code by doing something like this

cin>>userInput;
cin.ignore();

This will ignore everything present in the cin stream and you can continue with the code.

Some more explanation about cin.ignore is over here and here

Community
  • 1
  • 1
stranded
  • 312
  • 2
  • 9
0

Just use cin >>

    cout << "Please input the height: " << endl;
    cin >> userInputHeight;
    stringstream heightStream(userInputHeight);

If you need to get more than just the first word, and maybe what you meant to begin with, use cin.getline()

MrDuk
  • 16,578
  • 18
  • 74
  • 133