Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

C++ - Check input type

  • 24-03-2007 02: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