2013-03-24 89 views
2

我試圖做一個模數運算。我要求用戶輸入兩個數字,因爲模數只適用於整數,我有一個while循環來檢查輸入是否是整數。然後while循環要求用戶重新輸入這兩個數字。但while循環不斷重複,並且不允許用戶重新輸入數字。什麼是適當的去做這件事?C++ - 檢查輸入是否爲整數時循環不斷重複 -


#include <iostream> 
using namespace std; 

int Modulus (int, int,struct Calculator); 

struct Calculator 
{ 
    int per_numb1, per_numb2; 
    int per_Result; }; 

int main() 
{ 
    Calculator Operation1; 

    cout << "\nPlease enter the first number to calculate as a modulus: "; 
    cin >> Operation1.per_numb1; 

    cout << "\nPlease enter the second number to calculate modulus: "; 
    cin >> Operation1.per_numb2; 

while (!(cin >> Operation1.per_numb1) || !(cin >> Operation1.per_numb2)) 
{ 

     cout << "\nERROR\nInvalid operation \nThe first number or second number must be an integer"; 
     cout << "\n\nPlease re-enter the first number to begin Modulus: "; 
     cin >> Operation1.per_numb1; 

     cout << "\nPlease re-enter the second number to begin Modulus: "; 
     cin >> Operation1.per_numb2; 
} 





Operation1.per_Result = Modulus(Operation1.per_numb1, Operation1.per_numb2, Operation1); 

cout << "\nThe result is: " << Operation1.per_Result << endl; 

} 

int Modulus (int n1, int n2, struct Calculator) 
{ 
    int Answer; 

    Answer = n1 % n2; 

    return Answer; 
} 
+2

如果輸入失敗,你需要明確的輸入流。 – 2013-03-24 02:57:53

+0

我試過在while循環中使用cin.clear(Operation1.per_numb1)和cin.clear(Operation1.per_numb2),但仍然不起作用 – user2203675 2013-03-24 03:10:46

+0

[cin無限循環]的可能重複(http://stackoverflow.com/問題/ 5864540 /無限循環與cin) – sashoalm 2015-02-09 17:02:16

回答

3

重構到這樣的事情:

#include <iostream> 
#include <string> 
#include <limits> 

using namespace std; 

class Calculator 
{ 
public: 
    static int Modulus (int n1, int n2); 
}; 

int Calculator::Modulus (int n1, int n2) 
{ 
    return n1 % n2; 
} 

int getInt(string msg) 
{ 
    int aa; 

    cout << msg; 
    cin >> aa; 
    while (cin.fail()) 
    { 
     cin.clear(); 
     cin.ignore(std::numeric_limits<streamsize>::max(),'\n'); 
     cerr << "Input was not an integer!" << endl; 
     cout << msg; 
     cin >> aa; 
    } 
    return aa; 
} 

int main() 
{ 
    int num1 = getInt("Enter first value: "); 
    int num2 = getInt("Enter second value: "); 
    int value = Calculator::Modulus(num1,num2); 
    cout << "Answer:" << value << endl ; 
} 
+0

我還沒有學過類。我可以在原始程序中更改哪些具體內容,以使其正常工作? – user2203675 2013-03-24 03:35:12

+0

請勿使用while循環。相反,使用像我提供的'getInt()'這樣的函數。注意它是如何使用'cin.fail()'檢查錯誤的,以及它如何使用'cin.clear()'和'cin.ignore()'清除輸入流和錯誤。 – 2013-03-24 03:49:27

+0

謝謝。我使用了cin.ignore(std :: numeric_limits :: max(),'\ n'); – user2203675 2013-03-24 03:54:16

2

當輸入解析失敗,無效的輸入數據將保持在信息流中。您需要

  1. 通過調用cin.clear()來清除流錯誤狀態。
  2. 並跳過剩餘的無效輸入。

See the answer to this question.

+0

我到底會在哪裏調用cin.clear()。在我要求用戶重新輸入數字之後是否會出現這種情況? – user2203675 2013-03-24 03:20:34

+0

@ user2203675無法獲得用戶的號碼後。 – 2013-03-24 03:34:34

+0

你能告訴我一個我的程序的編輯副本,所以我可以看到確切的位置。我嘗試了你告訴我的,但它仍然不起作用。 – user2203675 2013-03-24 03:44:32