You can read a single character from the keyboard and store it in a variable of type char using the scanf() function with the format specifier %c:
char ch = 0; scanf("%c", &ch); // Read one character
To write a single character to the command line with the printf() function, you use the format specifier, %c:
printf("The character is %c\n", ch);
You can output the numeric value of a character:
printf("The character is %c and the code value is %d\n", ch, ch);
This statement will output the value in ch as a character and as a numeric value.
#include <stdio.h> int main(void) { char first = 'T'; char second = 63; printf("The first example as a letter looks like this - %c\n", first); printf("The first example as a number looks like this - %d\n", first); printf("The second example as a letter looks like this - %c\n", second); printf("The second example as a number looks like this - %d\n", second); return 0;/* w w w . j a va2 s . co m*/ }
You initialize the first variable with a character constant and the second variable with an integer.
The next four statements output the value of each variable in two ways:
printf("The first example as a letter looks like this - %c\n", first); printf("The first example as a number looks like this - %d\n", first); printf("The second example as a letter looks like this - %c\n", second); printf("The second example as a number looks like this - %d\n", second);
%c conversion specifier converts the contents of the variable as a single character.
%d specifier interprets it as an integer.
The numeric values that are output are the ASCII codes for the corresponding characters.