我在C ++中进行范围检查的逻辑有问题

时间:2019-06-13 16:46:56

标签: c++

int x = 0;

cout << "Input a number between 0 an 65535" << endl << endl;

while (!((cin >> x) && (0 < x < 65535)))
{
    cout << "\nEnter a valid number";
}

//..

如果数字太大,将进入无限循环

1 个答案:

答案 0 :(得分:5)

0 < x < 65535不是您想像的,您想要(0 < x) && (x < 65535)

还请注意,如果用户不输入 int cin >> x始终返回false,则需要清除错误并刷新输入

提案:

#include <iostream>
#include <limits>

using namespace std;

int main(void)
{
  int x;

  cout << "Input a number between 0 an 65535" << endl << endl;

  while (!(cin >> x) || (x < 0) || (x > 65535))
  {
    if (cin.rdstate()) {
      if (cin.rdstate() & istream::eofbit)
        // EOF
        return -1;

      cin.clear();
      // flush all the line, you can just read a word
      // with "string s; cin >> s;" if you prefer
      cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    cout << "Enter a valid number" << endl;
  }

  cout << x << " is valid" << endl;

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra c.cc
pi@raspberrypi:/tmp $ ./a.out
Input a number between 0 an 65535

not an int
Enter a valid number
-1
Enter a valid number
123
123 is valid
pi@raspberrypi:/tmp $