因此,我正在处理的这个程序没有按照我想要的方式处理不正确的用户输入。用户应该只能输入一个3位数字,以便稍后在HotelRoom对象构造函数中使用。不幸的是,我的教师不允许在他的班级中使用字符串对象(否则,我认为我不会有任何问题)。另外,我将roomNumBuffer传递给构造函数来创建一个const char指针。我目前正在使用iostream,iomanip,string.h,并限制了预处理器指令。尝试为roomNumBuffer输入太多字符后出现问题。下面的截图显示发生了什么: 不正确处理用户输入
此问题的相关代码如下:
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');
}
}
任何想法,将不胜感激。提前致谢。
作为第一个解析步骤,不使用'getline'是疯狂的。 [这样做。](http://stackoverflow.com/a/13445220/596781)。 –
@KerrekSB我同意,但我认为使用cin.width()可能有助于我试图完成的任务。当我尝试** getline **时,我遇到了同样的问题。如果使用它,我将如何处理这个问题? – Nyxm