我正在创建一个简单的控制台应用程序,用于获取用户输入的整数。当出现错误时返回第一条指令
我想要的状态,以便它应该只是一个整数,它应该是不超过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循环混淆了。
确保您正确缩进代码。如果你的'}'总是与时间排在一起,或者它属于的话,那么while循环变得不那么令人困惑。 – wolfgang 2013-05-14 13:36:55
也可以使用'{}'作为单行if语句。它提高了可读性和可维护性 – stefan 2013-05-14 13:39:36
@stefan它也是圣战的主题;-) – wolfgang 2013-05-14 13:40:32