简体   繁体   中英

Not handling user input correctly

So, this program I am working on is not handling incorrect user input the way I want it to. The user should only be able to enter a 3-digit number for use later in a HotelRoom object constructor. Unfortunately, my instructor doesn't allow the use of string objects in his class (otherwise, I wouldn't have any problems, I think). Also, I am passing the roomNumBuffer to the constructor to create a const char pointer. I am currently using the iostream, iomanip, string.h, and limits preprocessor directives. The problem occurs after trying to enter too many chars for the roomNumBuffer. The following screenshot shows what happens: 在此输入图像描述

The relevant code for this problem follows:

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');
    }
}

Any ideas would be greatly appreciated. Thanks in advance.

Read an integer and test whether it's in the desired range:

int n;

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

Although Kerrek SB provide an approach how to address the problem, just to explain what when wrong with your approach: the integer array could successfully be read. The stream was in good state but you didn't reach a space. That is, to use your approach, you'd need to also test that the character following the last digit, ie, the next character in the stream, is a whitespace of some sort:

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

It seems the error recovery for the first value isn't quite right, though. You probably also want to ignore() all characters until the end of the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM