Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

C++ - Check input type

  • 24-03-2007 2:08pm
    #1
    Registered Users, Registered Users 2 Posts: 590 ✭✭✭


    Hey,

    I'm just wondering whats the best way to check the input from a user to ensure its an interger in C++?
    int a;
    cout << "Enter an integer value: ";
    cin >> a;
    
    //Check to make sure its an integer???
    

    Is there some sort of type function to ensure the input is of type int?


Comments

  • Registered Users, Registered Users 2 Posts: 31 markkilpatrick


    you will need to have
    #include <ios>
    #include <limits>

    and then do this


    cin>>input;
    while(!cin)
    {
    cout<<"invalid input. Please enter an interger."<<endl;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin>>input;
    }


  • Registered Users, Registered Users 2 Posts: 590 ✭✭✭bman


    Thanks. Will give that a go.


  • Registered Users, Registered Users 2 Posts: 590 ✭✭✭bman


    This works if you input a string with a non numeric character as the first letter but not if the first character is a numeric character. For example, entering 35d still gets through. In this case it seems to take 35 as the integer value.

    Any ideas on this problem?


Advertisement