-
getch() / getche()
i was using getch() funtion and storing the result in a int variable. But it didn't work properly. I did an 'add watch' on the program to see what the int varibale was.
int num;
num = getch();
the add watch said num took on a value of 50 when i typed in the number 1, it also went to 49 when i typed in the number 2. Why can't getch() handle integers properly?
-
getch() returns the character you typed in. If you want the actual number value, try:
Code:
int theNum;
theNum = getch( ) - '0';
-
why the - '0'; part in
theNum = getch( ) - '0';
what is the - '0';
-
that causes the function to return the ASCII value of the character, hence a numerical value, rather than the alpha. Example, by this function if i enter "a" i would recieve from the function its numerical ASCII value which i think is 27...its too late i dont member the ASCII value.
-
Here's an ASCII table.
Say the user enters '4'. getch() will return 52. In order to get the actual number the user entered, subtract the ASCII value of 0 from it (48). 52-48=4
-
@Blanket: Try reading through the FAQ too.