我正在创建一个简单的控制台应用程序,它获取用户输入,它是一个整数。
我想要这个条件,它应该只是一个整数,它应该不超过 3 并且不小于 0。
到目前为止我提出的代码是:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int uinval;
while (true) {
string tempoval;
cout << "Please enter a value between 0-3:\n>";
cin >> tempoval;
stringstream ss(tempoval);
if (ss >> uinval)
{
break;
cout << "Entered an invalid value";
}
while (true)
{
if (uinval < 0 || uinval > 3)
break;
cout << "Value must be between 0-3";
}
cout << "You have entered:" << uinval;
return 0;
}
这在我输入一个非整数值(如 a、b、c、d)时有效。但是当我输入 -1 或 4 作为值时它不起作用。
我不确定,也许我对 while 循环感到困惑。