Search code examples
c++typechecking

to check type of input in c++


## To check type of data entered in cpp ##

int main()
{
    int num;
    stack<int> numberStack;
    while(1)
    {
        cin>>num;
        if(isdigit(num))
            numberStack.push(num);
        else
            break;
    }
return(0);
}

If I declare a variable as interger, and I input an alphabet, say 'B', instead of the number, can I check this behavior of user? My code above exits when first number is entered and does not wait for more inputs.


Solution

  • First of all, the std::isdigit function checks if a character is a digit.

    Secondly, by using the input operator >> you will make sure that the input is a number, or a state flag will be set in the std::cin object. Therefore do e.g.

    while (std::cin >> num)
        numberStack.push(num);
    

    The loop will then end if there's an error, end of file, or you input something that is not a valid int.