why is the below code not printing the ASCII value of the inputed character ?
Code:
#include<stdio.h>
int main()
{
int a;
int b=scanf("%d",&a);
printf("%d %c ",a,a);
return 0;
}
In this code if I am giving input as any character , it gives me output as character using %c format specifier but does not give me the ASCII code of that character using %d ,what is the issue here ,please guide me .
You can't scanf an A into an int. A is not an integer value. Most likely the A you see is the one you entered. The variable a now has an indeterminate value.
You need to scanf into a char to get the A accepted and then you display the char as %d and you should see the 65.
If that was the case that scanf did not read the character successfully then why is the value of b printed as 1 ?Since scaanf returns the number of inputs read successfully so if character A cannot get inside an int variable then why is the value of b =1 ?
The return value of scanf is meaningless if an error occurred.
If A is an int and scanf uses %c and I enter 65 the return is 1 and a is -858993610.
You have to check for any errors before you use that scanf return using feof and/or ferror.
Try not to get mired in this. Validating input is a lot of code. I tell students that when they are learning, do not try to validate input. If the program needs specific data then enter only valid values.
Not all compilers use ASCII encoding for chars. This may not matter for small demonstration programs but production software you get paid for needs to be more robust. If your program must return an ASCII code then IMHO you should write explicit conversion code rather than relying on the intrinsic conversion when you cast char to int.
Each compiler implementation is free to decide for itself if char is signed or unsigned. A compiler that doesn't conform to your expectations may cause your expression to compute the wrong value.
Comment