2012-11-20 69 views
0

因此,我正在处理的这个程序没有按照我想要的方式处理不正确的用户输入。用户应该只能输入一个3位数字,以便稍后在HotelRoom对象构造函数中使用。不幸的是,我的教师不允许在他的班级中使用字符串对象(否则,我认为我不会有任何问题)。另外,我将roomNumBuffer传递给构造函数来创建一个const char指针。我目前正在使用iostream,iomanip,string.h,并限制了预处理器指令。尝试为roomNumBuffer输入太多字符后出现问题。下面的截图显示发生了什么: enter image description here不正确处理用户输入

此问题的相关代码如下:

cout << endl << "Please enter the 3-digit room number: "; 
do {  //loop to check user input 
    badInput = false; 
    cin.width(4); 
    cin >> roomNumBuffer; 
    for(int x = 0; x < 3; x++) { 
     if(!isdigit(roomNumBuffer[x])) {  //check all chars entered are digits 
      badInput = true; 
     } 
    } 
    if(badInput) { 
     cout << endl << "You did not enter a valid room number. Please try again: "; 
    } 
    cin.get();  //Trying to dum- any extra chars the user might enter 
} while(badInput); 

for(;;) { //Infinite loop broken when correct input obtained 
    cin.get();  //Same as above 
    cout << "Please enter the room capacity: "; 
    if(cin >> roomCap) { 
     break; 
    } else { 
     cout << "Please enter a valid integer" << endl; 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    } 
} 
for(;;) { //Infinite loop broken when correct input obtained 
    cout << "Please enter the nightly room rate: "; 
    if(cin >> roomRt) { 
     break; 
    } else { 
     cout << "Please enter a valid rate" << endl; 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    } 
} 

任何想法,将不胜感激。提前致谢。

+0

作为第一个解析步骤,不使用'getline'是疯狂的。 [这样做。](http://stackoverflow.com/a/13445220/596781)。 –

+0

@KerrekSB我同意,但我认为使用cin.width()可能有助于我试图完成的任务。当我尝试** getline **时,我遇到了同样的问题。如果使用它,我将如何处理这个问题? – Nyxm

回答

2

读取一个整数,并测试它是否在所需范围:

int n; 

if (!(std::cin >> n && n >= 100 && n < 1000)) 
{ 
    /* input error! */ 
} 
+0

这会工作,但我需要有一个char数组传递给构造函数(接受char数组并创建一个const char指针)。 – Nyxm

0

虽然Kerrek SB提供的方法如何解决这个问题,只是为了解释什么时候错了你的做法:整数数组就能成功被阅读。溪流状态良好,但你没有到达一个空间。也就是说,用你的方法,你还需要测试的最后一个数,即后面的字符,该流中的下一个字符,是某种形式的空白:

if (std::isspace(std::cin.peek())) { 
    // deal with funny input 
} 

似乎错误尽管如此,第一个值的恢复并不完全正确。您可能还想要ignore()所有字符,直到行尾。