Search code examples
c++intdoubleinvalid-characters

Distinguishing between an int and a double


I've searched for this answer, and no one seems to know how to fix this error. I want the input to be strictly an int. If the input is a double, I want it to send an error.

int creatLegs = 0;
string trash;
bool validLegs = true;
do
{
    cout << "How many legs should the creature have? ";
    cin >> creatLegs;

    if(cin.fail())
    {
        cin.clear();
        cin >> trash; //sets to string, so that cin.ignore() ignores the whole string.
        cin.ignore(); //only ignores one character
        validLegs = false;
    }

    if (creatLegs > 0)
    {

        validLegs = true;
    }

    if (!validLegs)
    {
        cout << "Invalid value, try again.\n";
    }

} while (!validLegs);

It seems to almost work. It sends the error, but only after moving onto the next loop. How can I fix this? And why is it still showing the error message but still moving on before showing it?


Solution

  • I think that you should read data as string, and then check it char by char to verify that it is integer - if every char is a digit, then we have integer and we can parse it.

    Problem with streams is, that if you're trying to read integer but decimal is passed, it reads the number up to the dot. And this part is a proper integer, so cin.fail() returns false.

    Sample code:

    #include <iostream>
    #include <string>
    #include <cctype>
    #include <cstdlib>
    
    using namespace std;
    
    int main() {
        int creatLegs = 0;
        bool validLegs = true;
        do
        {
            cout << "How many legs should the creature have? ";
            string input;
            getline(cin, input);
    
            validLegs = true;
            for (string::const_iterator i = input.begin(); validLegs && i != input.end(); ++i) {
                if (!isdigit(*i)) {
                    validLegs = false;
                }
            }
    
            if (!validLegs)
            {
                cout << "Invalid value, try again.\n";
            } else {
                creatLegs = atoi(input.c_str());
            }
    
        } while (!validLegs);
    
        cout << creatLegs << endl;
    }
    

    This of course is not a perfect solution. If there any leading or trailing spaces (or any other characters like + or -), the program will fail. But you always can add some code to handle those situations, if you need to.