2014-03-14 146 views
0

下面是代碼,我的輸出,預期輸出如下。爲什麼函數立即完成一次循環,然後再次運行?

#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氣缸發生什麼事,是因爲它問我「請輸入高度:」,然後等待響應,然後詢問半徑輸入。

實際發生的情況是,它立即打印出兩條消息,然後告訴我我的輸入不正確,然後第二次正確運行。

+0

你將如何編寫這個更有效,也歡迎任何意見。 – trueCamelType

回答

2

當你cin>>userInput執行時,它僅讀取整數,並在流中保留換行符(當你按下回車鍵)。你的getline函數讀取直到找到一行已經存在於cin流中的行的結尾,這樣你的userInputHeight被讀取並且包含一個空行。

所以,你可以通過做這樣

cin>>userInput; 
cin.ignore(); 

這東西會不顧一切存在的CIN流中修復你的代碼,你可以用代碼繼續。

約cin.ignore一些更多的解釋是在herehere

0

只需使用cin >>

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

如果你需要得到的不僅僅是第一個字,也許你的意思是什麼開始說起,用cin.getline()

相關問題