下面是代碼,我的輸出,預期輸出如下。爲什麼函數立即完成一次循環,然後再次運行?
#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();
}
我希望當我按下1氣缸發生什麼事,是因爲它問我「請輸入高度:」,然後等待響應,然後詢問半徑輸入。
實際發生的情況是,它立即打印出兩條消息,然後告訴我我的輸入不正確,然後第二次正確運行。
你將如何編寫這個更有效,也歡迎任何意見。 – trueCamelType