我試圖做一個模數運算。我要求用戶輸入兩個數字,因爲模數只適用於整數,我有一個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;
}
如果輸入失敗,你需要明確的輸入流。 – 2013-03-24 02:57:53
我試過在while循環中使用cin.clear(Operation1.per_numb1)和cin.clear(Operation1.per_numb2),但仍然不起作用 – user2203675 2013-03-24 03:10:46
[cin無限循環]的可能重複(http://stackoverflow.com/問題/ 5864540 /無限循環與cin) – sashoalm 2015-02-09 17:02:16