【问题标题】:C++ -While loop keeps on repeating when checking if input is an integer-C++ - 当检查输入是否为整数时循环不断重复 -
【发布时间】:2013-03-13 17:52:23
【问题描述】:

我正在尝试进行模运算。我要求用户输入两个数字,因为模数仅适用于整数,所以我有一个 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; 
} 

【问题讨论】:

  • 如果输入失败,需要清空输入流。
  • 我尝试在 while 循环中使用 cin.clear(Operation1.per_numb1) 和 cin.clear(Operation1.per_numb2) 但仍然不起作用
  • infinite loop with cin的可能重复

标签: c++ while-loop modulus


【解决方案1】:

重构为这样的:

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

【讨论】:

  • 我还没有学过课程。我可以在原始程序中更改哪些细节以使其正常运行?
  • 不要使用你的 while 循环。相反,请使用我提供的 getInt() 之类的函数。请注意它如何使用cin.fail() 检查错误,以及如何使用cin.clear()cin.ignore() 清除输入流和错误。
  • 谢谢。我使用了 cin.ignore(std::numeric_limits::max(),'\n');
【解决方案2】:

当输入解析失败时,无效的输入数据将保留在流中。你需要

  1. 通过调用cin.clear()清除流错误状态。
  2. 并跳过剩余的无效输入。

See the answer to this question.

【讨论】:

  • 我将在哪里调用 cin.clear()。是在我要求用户重新输入数字之后吗?
  • @user2203675 ​​从用户那里获取号码失败后。
  • 你能给我看我的程序的编辑副本吗,这样我就可以确切地看到在哪里。我试过你告诉我的,但还是不行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 2017-10-30
  • 2020-02-15
  • 1970-01-01
  • 1970-01-01
  • 2015-06-20
  • 2022-06-17
相关资源
最近更新 更多