user1322915
user1322915

Reputation: 1291

How to check types in C++ in Qt

I need to check the type of the input being entered by the user and if it is not of desired type, i should print an error message. My code is:

int ClassInput::inputInt(QString str)
{
    signed int l;
    std::cout << str.toStdString();
    std::cin>>l;

    while(!l)
    {
        eh.handleError(1);
        std::cin>>l;
        cin.clear ();
        cin.ignore (1000, '\n');
    }
    return l;
}

but the problem is it is not printing the error message when a float value is being entered. Also, it is going to next step and performing the calculations as if right input is entered.

Some times it is infinitely printing the error statement. please can anyone correct my code?

Upvotes: 0

Views: 7217

Answers (2)

ragingbit
ragingbit

Reputation: 220

I think typeinfo is what you are looking for. This could be an example code for the case of a int as expected input from the user.

std::cin>>l;
QString input = typeid(l).name();
if(input.compare("int")) continue;

Upvotes: 1

richard.g
richard.g

Reputation: 3765

I think your problem is not about type checking, but value checking instead. So typeid is not actually a good choice.

Specifically about the solution to your problem. You should add more strict value checking on your input. It is not a good idea to store the user's input in an int variable. Because if the user type a float variable, it will be implicitly converted to int. So that's why your code is not printing the error message when a float value is being entered. But it won't affect your follow-up calculation.

One another thing, if the input is not digits, but characters, 0 will be assigned to your input variable.

In order to robustly check the input value, you should change the type of input variable to std:string and check if the string is a legal input. Possible routine to do this:

  1. check if there is non-digits.

  2. check if it is a legal digit according to your program needs.

So instead of just writing a coarse !l check, write another separate checking function and call it here.

Upvotes: 1

Related Questions