In the program i am converting the character datatype into integer but it is displaying the ASCII code of the character, why? what should i do to print 4 as output?
void fun(int x)
{
cout<<x;
}
int main()
{
char ch='4';
fun((int)ch);
return 0;
}
I have tried changing the parameter from 'int x' to 'char x' and then typecasting in cout as 'cout<<(int)x;'
Casting a char
to int
will do what it should, cast the stored value into an integer. When you say char ch='4';
, the variable holds the ASCII value of '4'
, it does not store the integer value 4
. So casting it will not give you the integer value 4
.
To get the integer value of ch
(get 4
from '4'
), we can subtract the integer value by '0' so that we get the actual integer value,
void fun(int x)
{
cout << x - '0';
}