Link to home
Start Free TrialLog in
Avatar of jyhiroko
jyhiroko

asked on

Limiting Input

Hi I need help on limiting input. That is to only allow the user to enter 1 char. I'm doing a program that has a menu, and that i would want to allow the user to only enter 1 digit and nothing more.

Eg.
Choice -> 1 (expected to see only 1 if the users enter "1bc" it still only shows 1 unless the user enter 2* or 3 and so forth.
so we won't see

Choice -> 1a
Choice -> 11
Choice -> bb
etc
Enter is required to proceed which is why i din use getch() after that using isdigit to double check.


Thanks for any help that can be rendered.
Avatar of Zyloch
Zyloch
Flag of United States of America image

Hi jyhiroko,

Might not be the best way, and I'm not sure if C has some function like charAt, but you can use strncpy is one way:

http://www.harpercollege.edu/bus-ss/cis/166/mmckenzi/lect11/l11c.htm

Regards,
Zyloch
You can implement your own input function. Something like

int GetOption()
{
    char key;
    char option=0;

    do {
        key = getch();
        if (isdigit(key)) {
            option = key;
            putch(option);
        } else if (key==8) {  /* backspace */
            option = 0;
            putch(8);
        } else if (key==13) {  /* enter */
            if (option)
                return option;
        }
    }
}

SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Change this line:
> if(key==13) break;

to

if(key==13 && option!=-1) break;

This will keep asking for a digit even if the user presses enter without entering a digit.