Thread: Hault!

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    70

    Hault!

    Lets suppose I have an integer called number. Would it be possible to set boundaries on that integer so it is not possible to input a number larger than say 30000. I don't mean after you press enter, it runs some code to check if number>30000. I mean, at runtime, before you press enter...is it possible to physically not let the person enter a number higher than 30000, or if not, is it possible to not allow them to enter a number over so many digits?

  2. #2
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    Not really... unless you use a non-standard way to control each keypress of the user.

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    I guess you'd have to write your own input function then. This is one I've made (uses conio.h):
    Specify 0 as the parameter if you don't wish to have an upper limit. This might be useful too since it only accepts digits (not letters/other characters).
    Code:
    #include <iostream>
    #include <conio.h>
    
    using namespace std;
    
    
    #define MAXDIGITS 9
    
    
    int ReadNumber(int MaxNumber)
    {
    	//Data
    	int i;
    	char Key = 0;
    	char Buffer[MAXDIGITS] = {'0'};
    	int CurrentPointer = 0;
    	int Result = 0;
    
    	//Loop until ENTER is pressed
    	while((Key != (char)13) || (CurrentPointer == 0))
    	{
    		//Get the next keypress
    		Key = getch();
    
    		//The user pressed a digit
    		if((Key >= '0') && (Key <= '9') && (CurrentPointer < (MAXDIGITS - 1)))
    		{
    			//Accept the input only if it doesn't exceed the limits
    			if((MaxNumber == 0) || (((Result * 10) + (int)(Key - '0')) <= MaxNumber))
    			{
    				Buffer[CurrentPointer] = Key;
    				CurrentPointer++;
    				cout << Key;
    			}
    		}
    		//The user pressed BACKSPACE
    		else if((Key == '\b') && (CurrentPointer > 0))
    		{
    			Buffer[CurrentPointer] = '0';
    			CurrentPointer--;
    			cout << '\b';
    			cout << ' ';
    			cout << '\b';
    		}
    
    		//Calculate the result
    		Result = 0;
    		for(i = 0; i <= (CurrentPointer - 1); i++)
    		{
    			Result *= 10;
    			Result += (int)(Buffer[i] - '0');
    		}
    	}
    
    	//Return the number
    	return Result;
    }
    
    
    //Test
    int main()
    {
    	int X;
    
    	cout << "Enter a number: ";
    	X = ReadNumber(500);
    	cout << endl << "Your input was: " << X << endl;
    
    	return 0;
    }
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed