Is the code below converting a character into its ASCII value?
Is the code below converting a character into its ASCII value?.
I faced a piece of code while studying evaluation of postfix operation,where it says "the expression converts a single digit character in C to its numerical value".?in开发者_开发技巧t x=getch();
int c=x-'0'; /*does c have the ASCII value of x?*/
printf("%d",c);
No, it's converting the ASCII value to a number >= 0.
Let's say you type '1'. getch()
will return 49 which is the ASCII value of '1'. 49 - '0' is the same as 49 - 48 (48 being the ASCII value for '0'). Which gives you 1.
Note that this code is broken if you enter a character that is not a number.
E.g. if you type 'r' it will print 'r' - '0'
= 114 - 48
= 66
(Ref.)
No, it's giving the numeric value of a digit. So '5' (53 in ASCII) becomes 5.
Is the code below converting a character into its ASCII value?
It isn't. It's doing the opposite (converting an ASCII value to the numerical value) and it only works for decimal digits.
To print the ascii value all you need to do is :
int x=getch();
printf("%d",x);
If you are sure that you only want to accept integers as input then you need to put some constraints to the input before proceeding to process them.
int x = getch();
if (x >='0' || x <= '9') {
int c = x - '0'; // c will have the value of the digit in the range 0-9
. . .
}
Any character(in your case numbers) enclosed within single quotes is compiled to its ASCII value. The following line in the snippet above translates to,
int c=x-'0'; ---> int c= x-48; //48 is the ASCII value of '0'
When the user inputs any character to your program, it gets translated to integer as follow,
If x = '1', ASCII of '1' = 49, so c= 49-48 = 1
If x = '9', ASCII of '9' = 57, so c= 57-48 = 9 and so on.
精彩评论