mercredi 7 octobre 2020

How to not accept a float when inputting an int in c++

I am currently trying to write a program at school involving a random number generator for rolling a dice. I have written the code successfully, but I am trying to improve it so that the size of the dice and the number the user is trying to roll can be chosen by the user.

I have written code that does this, and I have also added code that repeats the request for input if the wrong value (ie not one of the dice sizes offered or trying to roll a number outside the range of the dice) or input type (ie var instead of int) is entered. However, if a floating point number is entered, and the number to the left of the floating point is in the correct range of values, it is using that number.

For example:

    int size = 0;
    cout << "Please choose the size of the dice to roll (6, 12 or 20): ";
    cin >> size;

    while (size != 6 && size != 12 && size != 20 || !cin)
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid number entered. Choose the size of the dice to roll (6, 12 or 20): ";
        cin >> size;
    }

This will correctly ask to repeat the input if any letters or any numbers that aren't 6, 12 or 20 are entered, but if 20.125 (or any floating point number that is 6.- 12.- or 20.-) is entered it will take the number and move on to the next bit of code. This also happens if I enter a valid number followed by letters (ie 6f).

I tried modifying the condition of the while loop to:

    while (size != 6 && size != 12 && size != 20 || !(cin >> size))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid number entered. Choose the size of the dice to roll (6, 12 or 20): ";
        cin >> size;
    }

And that fixes the problem, and it asks me for another input if I enter 12.5 or 20R etc, but then when I enter a correct input (6, 12 or 20) it just takes me to a new line in the debugger without moving to the next line of code. If I then enter a correct input again, it reads it at takes me to the next line of code.

Thanks in advance, any guidance is much appreciated!

Aucun commentaire:

Enregistrer un commentaire