C Tutorial/Data Type/char read

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

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

ASCII code values range from 0 to 127.


#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);
}
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)

#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);
}
Type your favorite keyboard character:
      1
      Your favorite character is 1!

Reading characters and strings

#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; 
}
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.


#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);
}
Type your favorite keyboard character:
      1
      Your favorite character is 1!