3

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++;
        }
linoiushi
  • 47
  • 6

2 Answers2

1

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Change

if(userDigit<=6 && userDigit>=1)

to

if(userDigit<='6' && userDigit>='1')

That will work because '0', '1', ... symbols have consequential ASCII codes so the comparisons are valid.

Anton Malyshev
  • 8,686
  • 2
  • 27
  • 45