我正在尝试在C ++中创建一个验证循环,该循环检查用户的输入,直到他们输入0到100之间的数字为止,但是我的循环仅检查第一个条件。任何指导表示赞赏!
#include <iostream>
using namespace std;
int main()
{
const int max_num = 100;
const int min_num = 0;
int num;
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
do {
if (!(cin >> num))
{
cout << "ERROR:The value provided was not a number" << endl;
cin.clear();
cin.ignore(1024, '\n');
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
}
else if (num<min_num || num>max_num)
{
cout << "ERROR: value out of range" << endl;
cin.clear();
cin.ignore(1024, '\n');
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
}
} while (!(cin >> num) || (num<min_num || num>max_num));
return 0;
}
答案 0 :(得分:0)
在代码中添加大量日志,以便您了解代码的作用。这将帮助您发现问题。例如,代替:
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
尝试:
cout << "Enter a number between 0 and 100" << endl;
cerr << "About to read into num outside the loop" << endl;
cin >> num;
cerr << "Read into num outside the loop, got: " << num << endl;
依此类推,贯穿整个代码。这应该给您足够的信息来查找错误。另外,也可以使用具有单步功能的调试器来完成相同的任务。
答案 1 :(得分:0)
在一段时间内检查一下:
代替
while (!(cin >> num) || (num<min_num || num>max_num));
此:
while (!cin || (num<min_num || num>max_num));
如果上方则相同
答案 2 :(得分:0)
cin >> num
意味着将用户输入放到变量num
中。因此,您试图在循环中两次接受用户输入。也许检查条件:(num == (int)num)
将解决您的问题。它将尝试验证您存储在num
中的号码确实是int