如果给定的条件类型错误,则 C++ 无限 while 循环

标签 c++ while-loop

[更新]我有以下 C++ 代码(跳过不必要的细节):

#include <iostream>

using namespace std;
int main() {
    double value;
    double sum = 0;
    double max, min;
    string msg = "Enter next value (-1) to end: ";
    int validCounter = 0;

do{
    cout << msg;
    cin >> value;  // Values assumed to be numbers
}
while (value <= 0 and value != -1);

if (value > 0.0){sum+= value, max = value, min = value, validCounter = 1;}  // Initial values of min, max, validCounter = 1
while (value != -1){
    cout << msg;
    cin >> value;

    // Only take positive values into consideration for stats
    if (value > 0) {
        validCounter++;
        sum += value;
        if (value > max) { max = value; }
        if (value < min) { min = value; }
    }
}
cout << to_string(validCounter) + " valid value(s) entered" << endl;
if (validCounter > 0){
    cout << "Minimum: " + to_string(min) << endl;
    cout << "Maximum: " + to_string(max) << endl;
    cout << "Moyenne: " + to_string(sum/validCounter) << endl;
}

return 0;

}

但是,当提示输入一个值(为了简单起见,应该是一个数字,这是一个初学者程序)时,如果输入的值不是双倍,则 while 循环开始无限显示输入提示。为什么是这样?是否是由于比较 String != -1 (或任何其他非 int/double 类型)导致循环重复?我在这里很困惑。

最佳答案

替换

do{
    cout << msg;
    cin >> value;  // Values assumed to be numbers
}
while (value <= 0 and value != -1);

do {
  cout << msg;
  if (!(cin >> value)) {
    string dummy;

    cin.clear();   // to be able to read double
    cin >> dummy; // to remove the non float
    value = 0;
  }
  while (value <= 0 and value != -1);

您需要清除错误才能再次读取,然后绕过错误的输入,也许您也可以只读取一个字符,决定发生错误时该怎么办

示例:

#include <iostream>
using namespace std;

int main()
{
  double value;

  do {
    cout << "value please" << endl;
    if (!(cin >> value)) {
      string dummy;

      cin.clear();
      cin >> dummy;
      value = 0;
    }
  } while (value <= 0 and value != -1);

  cout << "valid double :" << value << endl;
  return 0;
}

编译和执行:

% ./a.out
value please
aze
value please
-12
value please
12
valid double :12

关于如果给定的条件类型错误,则 C++ 无限 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54782740/

相关文章:

c++ - 使用 CGAL 进行网格 bool 运算

java - 将 Borland C++ 代码转换为 Java 代码

c++ - 同时从多个流中捕获,最好的方法以及如何减少 CPU 使用率

c++ - GCC 精选优化

javascript - 在复杂例程中使用多个值的最简洁方法?

c++ - 当char数组被过度填充时,为什么我的程序会陷入无限循环?

linux - while循环出错?脚本

c++ - boost asio 示例测试失败

c - 在 C 中循环数字总和(输入)

java - while循环Int return方法内部完全死了