dimanche 29 avril 2018

How to stop C++ from automatically converting double to int?

How do I stop C++ from automatically converting double to int values? I get that this is by design, but I don't want it to.

My code in question is as follows:

double validateInput()
{
    int n = {};
    cin >> n;

    while (cin.fail() || (n < 1) || (n > 999))
    {
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        n = {};

        cout << "Please enter a valid number:" << endl;
        cin >> n;

    }

    cout << "n = " << n << endl; 
    return (double)n;
}

The function is supposed to to take an integer value and return an error if anything but an integer value is entered. However, since C++ converts double to int by design, converted double values still get through.

Aucun commentaire:

Enregistrer un commentaire