• C

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.
jyhirokoAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
ankuratvbConnect With a Mentor Commented:
Hope this is what you're looking for.It allows you to enter only one digit,if you enter another digit after you've already entered one,the previous digit is replaced with the new digit.

The value is accepted only when you press enter.

char GetOption()
{
   char key;
   char option=-1;

   do {
       key = getch();
       if(key==13) break;
       if (isdigit(key)) {
         option = key;
         if(option!=-1)
            putch(8);
         putch(option);
       }
   } while (1);  /* Infinite loop */
   return option;
}

int main()
{
char ch;
ch=GetOption();
printf("%c",ch);
}
0
 
ZylochCommented:
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
0
 
Jaime OlivaresSoftware ArchitectCommented:
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;
        }
    }
}

0
 
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
Sorry, some mistakes (writting from my memory);

char 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)
                break;
        }
    } while (1);  /* Infinite loop */
    return option;
}
0
 
ankuratvbCommented:
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.