2013-10-20 74 views
1
do 
{ 
    cout << "Enter the numerator and denominator of the first fraction: "; 
    cin >> a >> b; 
    cout << endl; 
    cout << "Enter the numerator and denominator of the second fraction: "; 
    cin >> c >> d; 
    cout << endl; 
} while (!validNum(a, b, c, d)); 

... 

bool validNum(int num1, int num2, int num3, int num4) 
{ 
    if (cin.fail() || num2 == 0 || num4 == 0) 
    { 
     if (num2 == 0 || num4 == 0) 
     { 
      cout << "Invalid Denominator. Cannot divide by 0" << endl; 
      cout << "try again: " << endl; 
      return false; 
     } 
     else 
     { 
      cout << "Did not enter a proper number" << endl; 
      cout << "try again: " << endl; 
      return false; 
     } 
    } 
    else 
     return true; 
} 

我想要做的是確保分母不爲零,並且他們只輸入數字。除零代碼的工作正常,但是當你輸入一個char值時,它會進入一個無限循環,不知道爲什麼。有任何想法嗎?無效int輸入陷入無限循環

回答

2
if (cin.fail() ...) 

一旦你輸入無效值(即一個char),流中的failbit將會對和validNum總是會返回false,導致一個無限循環。

你需要在每次通話後清除錯誤狀態並忽略輸入的其餘部分:

if (std::cin.fail()) 
{ 
    std::cin.clear(); 
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
} 
+0

真棒它的作品完美。出於好奇,numeric_limits :: max()是如何工作的以及它做了什麼 –

+0

@JuanSierra ['numeric_limits :: max'](http://en.cppreference.com/w/cpp/types/numeric_limits/max)返回給定類型的最大值。 – 0x499602D2