C Tutorial/Data Type/char

Материал из C\C++ эксперт
Версия от 13:32, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Characters and numbers

<source lang="cpp">#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;

}</source>

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


<source lang="cpp">#include <stdio.h> main() {

   char i = 65;
  
   printf("%c", i);

}</source>

A

Define escape sequence in a char

<source lang="cpp">#include <stdio.h>

int main() {

   char tab="\x9C";
  
   printf("a%cb",tab);
  
   return 0;

}</source>

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

<source lang="cpp">#include <stdio.h>

int main() {

   char tab="\t";
  
   printf("a%cb",tab);
  
   return 0;

}</source>

a    b

Using type char

<source lang="cpp">#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;

}</source>

Character values      C    A    \
     Numerical equivalents 67   65   92
     The number 40 is the code for the character (