C Tutorial/Data Type/char read

Материал из C\C++ эксперт
Перейти к: навигация, поиск

All letters of the alphabet, symbols, and number keys on the keyboard have ASCII codes

ASCII code values range from 0 to 127.


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

int main() {

   char key;

   printf("Press a key on your keyboard:");
   key=getchar();
   printf("You pressed the "%c" key.\n",key);
   printf("Its ASCII value is %d.\n",key);
   return(0);

}</source>

Press a key on your keyboard:1
      You pressed the "1" key.
      Its ASCII value is 49.

Reading and Writing Single Characters: scanf(%c,&key)

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

int main() {

   char key;

   puts("Type your favorite keyboard character:");
  
   scanf("%c",&key);
  
   printf("Your favorite character is %c!\n",key);
  
   return(0);

}</source>

Type your favorite keyboard character:
      1
      Your favorite character is 1!

Reading characters and strings

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

  char x;      
  char y[ 9 ]; 
  
  printf( "Enter a string: " );
  scanf( "%c%s", &x, y );
  printf( "The input was:\n" );
  printf( "the character \"%c\" ", x );
  printf( "and the string \"%s\"\n", y );
  return 0; 

}</source>

Enter a string: string
The input was:
the character "s" and the string "tring"

The getchar() function

The getchar() function is used to read a single character from the keyboard.


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

int main(){

   char key;

   puts("Type your favorite keyboard character:");
   key=getchar();
   printf("Your favorite character is %c!\n",key);
  
   return(0);

}</source>

Type your favorite keyboard character:
      1
      Your favorite character is 1!