C++ -当检查输入是否为整数时,循环不断重复 -

标签 c++ while-loop modulus

我正在尝试进行模数运算。我要求用户输入两个数字,因为模数仅适用于整数,所以我有一个 while 循环来检查输入是否为整数。然后 while 循环要求用户重新输入这两个数字。但是 while 循环不断重复并且不允许用户有机会重新输入数字。这样做的正确做法是什么?


#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; 
} 

最佳答案

重构为这样的:

 #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 ;
 }

关于C++ -当检查输入是否为整数时,循环不断重复 -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15594654/

相关文章:

c++ - ARM 汇编和 C++

python - 我的 while 循环一遍又一遍地重复

javascript - 在php while循环中单击按钮时获取特定div

c++ - 在定点类型上实现模数

C++ Vector.erase() 最后一个元素破坏了迭代器

c++ - 如何减少用 native Visual C++ 编写的大型项目的链接时间?

javascript - 通过 NaiveSort 算法 JavaScript 循环问题

java - 如果一次满足值则停止循环一次

c - 为什么模运算符不扩展到除整数类型之外的其他数据类型?

C++:POD 优缺点