2013-05-14 55 views
1

我正在创建一个简单的控制台应用程序,用于获取用户输入的整数。当出现错误时返回第一条指令

我想要的状态,以便它应该只是一个整数,它应该是不超过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循环混淆了。

+1

确保您正确缩进代码。如果你的'}'总是与时间排在一起,或者它属于的话,那么while循环变得不那么令人困惑。 – wolfgang 2013-05-14 13:36:55

+0

也可以使用'{}'作为单行if语句。它提高了可读性和可维护性 – stefan 2013-05-14 13:39:36

+1

@stefan它也是圣战的主题;-) – wolfgang 2013-05-14 13:40:32

回答

3

这是不正确的:

while(true){ 
    if(uinval < 0 || uinval > 3) 
    break; 
    cout <<"Value must be between 0-3"; 
} 

您检查车况上uinval反复,不给用户有机会输入一个新值。

要解决此问题,删除第二个循环,并与

if(ss >> uinval && uinval >= 0 && uinval < 4) { 
    break; 
} 
0

你有你的if语句抱着你希望它是什么相反更换

if(ss >> uinval) { 
    break; 
} 

第一循环中。

现在,如果该值低于0或大于3,则会中断并继续。如果超过0且小于3,则希望它继续。

if(uinval > 0 && uinval < 3)