DavidJ85 DavidJ85 - 1 month ago 8
C++ Question

How to create a catch for data type

I have been making some simple programs such as number guessing games, betting games, etc. One thing I am trying to do in these programs is to create a catch for inputting the wrong data type. So if I had the variable

int num;
and the user inputted a string, is there a way to recognize if the data entered does not match the data type of the declared variable and ask to re-input it?

Thanks.

Answer

The C++ IOstream library does that for you. by default, std::istream objects will fail if formatted extraction operations fail.

So when you have something like this.

int num;

if(!(std::cin >> num)){
    //operation failed
}

If the user enters characters other than numbers. std::cin will fail. Hence all you need to do is to check the status of the stream object to know if a formatted input succeeded

is there a way to recognize if the data entered does not match the data type of the declared variable and ask to re-input it?

You could do something like this:

#include <limits> //for std::numeric_limits
#include <ios>    //for std::streamsize
......

int num;
while(!(std::cin >> num)){
    std::cerr << "Please enter a valid number!\n";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

EDIT:

As user4581301 pointed out in the comment, there are a few corner cases to watch out for.

A slight improvement hack for ints/floats hullabalo may be:

while(!(std::cin >> num) || std::cin.get() == static_cast<int>('.') ){
    std::cerr << "Please enter a valid number!\n";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Note, that this hack only applies to ints