Getting infinite loop instead of a value

123 Views Asked by At

This is the problem below.

I am getting an infinite loop instead of int type of data in the do-while loop

#include <iostream>
#include <typeinfo>
int main()

{
    int in; // variable in;

    do //loop for check if variable get valid data
    {

        std::cout << "enter : ";

        std::cin >> in;

        if (typeid(in) == typeid(int()))
            break;
        else
            std::cout << "invalid input !! " << std::endl;
    } while (true);
}
3

There are 3 best solutions below

1
anastaciu On BEST ANSWER

The condition

if (typeid(in) == typeid(int()))

will evaluate to false.

For it to evaluate to true you will need

if (typeid(in) == typeid(int))

Running sample

But, as already said, if what you want is to check for correct inputs, this is not the way to go.

2
con ko On

Although you use RTTI, the type of in is fixed at compile time. Plus, here you cannot directly compare the typeid of a int variable and a function type. They won't be the same. So such a design is nonsense. To check whether the input satisfy the requirement of integer input. Basically you have two ways:

  1. Check whether the failbit of cin is set.
  2. read a string instead and check whether each character in the string is digit.
0
Jarod42 On

typeid(in) == typeid(int()) is equivalent to typeid(int) == typeid(int()) as in is a int.

int() is a signature of function: taking no parameter, and returning int.

So different than type int.

Way to check input validity is to check std::cin status.