所以,我正在开发的这个程序并没有按照我想要的方式处理不正确的用户输入。用户应该只能输入一个 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');
}
}
任何想法将不胜感激。提前致谢。