C Tutorial/Data Type/char
Содержание
Characters and numbers
#include <stdio.h>
int main(void)
{
char first = "T";
char second = 20;
printf("\nThe first example as a letter looks like this - %c", first);
printf("\nThe first example as a number looks like this - %d", first);
printf("\nThe second example as a letter looks like this - %c", second);
printf("\nThe second example as a number looks like this - %d\n", second);
return 0;
}
The first example as a letter looks like this - T The first example as a number looks like this - 84 The second example as a letter looks like this - The second example as a number looks like this - 20
Data type char are stored internally as integers
Data type char can have 8 bits, so you can have 256 different character values (0-255).
"A" is represented as decimal value 65
#include <stdio.h>
main()
{
char i = 65;
printf("%c", i);
}
A
Define escape sequence in a char
#include <stdio.h>
int main()
{
char tab="\x9C";
printf("a%cb",tab);
return 0;
}
a?
Escape sequences
Escape sequence Value \a alert (bell) character \\ backslash \b backspace \? question mark \f form feed \" single quote \n new line \" double quote \r carriage return \ooo octal number \t horizontal tab \xhh hexadecimal number \v vertical tab
Save Tab key into a char, you use an escape sequence
#include <stdio.h>
int main()
{
char tab="\t";
printf("a%cb",tab);
return 0;
}
a b
Using type char
#include <stdio.h>
int main(void)
{
char first = "A";
char second = "B";
char last = "Z";
char number = 40;
char ex1 = first + 2;
char ex2 = second - 1;
char ex3 = last + 2;
printf("Character values %-5c%-5c%-5c", ex1, ex2, ex3);
printf("\nNumerical equivalents %-5d%-5d%-5d", ex1, ex2, ex3);
printf("\nThe number %d is the code for the character %c\n", number, number);
return 0;
}
Character values C A \ Numerical equivalents 67 65 92 The number 40 is the code for the character (