check if input is an integer
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: check if input is an integer

  1. #1
    Join Date
    Jun 2014
    Posts
    7

    check if input is an integer

    I have been trying to make a very simply programme that checks if the inputted information is an integer or not (i.e: that it contains no other characters).

    I have tried using the isdigit function (but this only works for single characters)
    i have tried cin.clear, cin.ignore (1000) but this doesn't work either..

    can someone please suggest an effective way to check if x in the following programme has been entered correctly

    #include <iostream>
    using namespace std;

    int main()
    {
    cout << "Please enter an integer (positive or negative)" << endl;
    int x;
    cin >> x;
    HERE I WOULD LIKE CODE TO CHECK IF THE USERS INPUT IS VALID
    }

    thanks

  2. #2
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,327

    Re: check if input is an integer

    If the input isn't valid for the type expected for stream extraction, then the state of the stream changes from good to fail. So to check that the users input was valid, check that the state of the stream is not good. See http://www.cplusplus.com/reference/ios/ios/fail/.

    The easiest way to do this is
    Code:
    if (cin >> x) {
    //input was good
    } else {
    //input was bad
    cin.clear();
    }
    or often
    Code:
    while (cin >> x) {
    //stream good code
    }
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  3. #3
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    3,835

    Re: check if input is an integer

    if you want a "could a string be interpreted as an integer" type routine that is independant of io (you don't need the actual int value), then the obvious way to test this is via a regex.

    if you want the actual int value out of that too, then io streams, or stringstream would be the way.

    alternatively you can also do it "oldschool" style with strtoul()

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center