Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

after getch() the program ignores the if even after putting 1-6.

I have a problem with my code. It always ignoring the if(userDigit<=6 && userDigit>=1).. Can someone tell me what is wrong here?

        for(i=0; i<4; i++)
        {
            userDigit=getch();
            putch(userDigit);

            if(userDigit<=6 && userDigit>=1)
            {
                //code              
            }
            else
            {
               correct=0;
            }                       
        }

        if(correct == 0)
        {
            printf("wrong");
            correct++;
        }
like image 981
linoiushi Avatar asked Nov 24 '25 12:11

linoiushi


1 Answers

getch() returns a int representing the encoded value of the input character, not the digit itself.

Fortunately the C standard allows you to write

userDigit = getch() - '0';

to transform to the actual numerical value of the digit. Any non-digit input will be outside the range (0 - 9). (For the avoidance of doubt '0' is an int type in C.)

Naturally that will break your putch function (crudely you could transform back by adding '0'), but I suspect you have it there for debugging purposes and you can safely remove it.

like image 93
Bathsheba Avatar answered Nov 27 '25 03:11

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!