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

C++ - Check input type

Options
  • 24-03-2007 3:08pm
    #1
    Registered Users 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 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 Posts: 590 ✭✭✭bman


    Thanks. Will give that a go.


  • Registered Users 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