mardi 7 mars 2023

How to create a function that expects an integer value within a range, and decimal values are not accepted, either separated by dot or comma

I'm trying to create a function that expects a value, as I use it in several parts of the code. I would like to add these protections in case some invalid value is typed (decimal or out of range).

unsigned short getChoice(short min, short max) {
    short choice;
    bool valid = false;

    while (!valid) {
        std::cin >> choice;

        if (std::cin.fail() || choice < min || choice > max) {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Invalid Choice, Try Again.\n" << std::endl;
        }
        else {
            valid = true;
        }
    }
    return choice;
}

I got to this code, but it has several problems, as it accepts decimal numbers, rounds down, even if this is not explicit in the code. It's behavior I don't understand.

another problem is that when a number is invalid, when pressing enter, it is pulled by the next std::cin, which naturally shouldn't happen. How do I clear this value?

Aucun commentaire:

Enregistrer un commentaire