samedi 28 septembre 2019

cin.fail not working when numbers and letters entered

I am working on a simple data validation as part of inputting numbers to an array. Right now it is working for the most part with the exception of one case - when I enter a number followed by a letter, the error message that I created it thrown, but the number is still entered into the array. Further confusing me is that it is functioning as intended when I compile the program in Xcode, but the issue I'm describing only shows up when I compile the program with g++. Any thoughts would be very appreciated. Here is my function which I think is giving me the issue.

float getInput()
{
    float input;
    std::cin >> input;
    if (std::cin.fail())
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "type char/str not allowed, enter int" << '\n';
        return getInput();
    }
    else
        return input;
}

Aucun commentaire:

Enregistrer un commentaire