Results 1 to 3 of 3

Thread: user input

  1. #1

    Thread Starter
    Addicted Member DarkMoose's Avatar
    Join Date
    Jul 2000
    Location
    in a box
    Posts
    185

    user input

    If i want to have the user input an integer, how can i prevent them from entering a character without getting a run-time error?
    To understand recursion, one must first understand the concept of recursion.

  2. #2
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256
    What I usually do (and I doubt it's the best method), is have it input to a char, and then cast it to an integer, if it's valid.
    My evil laugh has a squeak in it.

    kristopherwilson.com

  3. #3
    Hyperactive Member Comreak's Avatar
    Join Date
    Feb 2001
    Location
    Dis
    Posts
    319
    You could handle the error... I usually just put user input into a while loop and have a function check to see if an error has occured in cin. I can't explain it very well, here's some code:

    This is the function I use to check cin.
    Code:
    short ErrChk()
    {
    	if(cin.fail())
    		{
    			cerr << "\nInput Error!  Clearing buffer... \n";
    			cin.clear();
    			cin.ignore(cin.rdbuf()->in_avail());
    			return 0;
    		}
    		else
    		{
    			return 1;
    		}
    }
    I know this doesn't catch every single possible case (I'm still looking for a way to do this). For example, if you enter "3abc", it will take 3 but the rest causes an error. Apparently, it only looks at the first value.

    Casting a char as an int is probably one of the better ways to go.

Posting Permissions

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



Click Here to Expand Forum to Full Width