#include<stdio.h>
int main(){
printf("%d\n", (int)('a'));
printf("%d\n", (char)(97));
}
Why does the program above give the output
97
97
instead of
97
a
CodePudding user response:
97, 0x61 and 'a' are just different ways of producing the same int value (at least on an ASCII-based machine).
And char is just another integer type, so casting the value to a char isn't going to help.
To print that value as a, use %c.
#include <stdio.h>
int main(void) {
printf("%d\n", 97); // 97
printf("%d\n", 'a'); // 97
printf("%c\n", 97); // a
printf("%c\n", 'a'); // a
}
CodePudding user response:
In the second call you are trying to output a character as an integer using the conversion specifier %d.
printf("%d\n", (char)(97));
Instead you could just write using the conversion specifier %c
printf("%c\n", 97);
In this case the casting is not required.
Pay attention to that even if you will write
printf("%c\n", (char)(97));
or
char c = 'a';
printf("%c\n", c);
nevertheless the second argument expression will be promoted to the type int due to the integer promotions.
Also in C integer character constants like 'a' have the type int.
CodePudding user response:
#include<stdio.h>
int main(){
printf("%d\n", (int)('a'));
printf("%c\n", (char)(97));
}
char is an integral type (same as int, long, long long etc etc), only ranges are different.
%d printf integer, character constant 'a' has type int and value 97 in ASCII.
You do not need casts in your example:
#include<stdio.h>
int main(){
printf("%d\n", 'a');
printf("%c\n", 97);
}
CodePudding user response:
What you want is printing a character, but in your second printf call you specify format %d instead of %c, then printf output your (char)(97) as an integer.
CodePudding user response:
Because you need write %c, not %d in the last line.
printf("%d\n", (char)(97));
to
printf("%c\n", 97);
CodePudding user response:
#include<stdio.h>
int main(){
printf("%d\n", (int)'a');
printf("%c\n", (char)97);
}
test it and see it works or not
