Publicité
Publicité

Contenu connexe

Publicité

5 1. character processing

  1. Character Processing
  2. The Use of getchar() and putchar()  getchar() – Gets a character (an unsigned char) from stdin. – It reads a character after you hit Enter key • After you hit Enter key, all of characters move to stdin butter. – getchar() returns a single char at a time. c = getchar(); /* It stores c variable after reading a char */ 2
  3. The Use of getchar() and putchar()  putchar() – Output a char on the screen. [Ex] #include <stdio.h> SKKU int main(void) { putchar(‘S’); putchar(‘K’); Only one char is used putchar(‘K’); in putchar(‘ ‘) putchar(‘U’); } 3
  4. The Use of getchar() and putchar()  Example [Ex] [Ex] c = getchar() ; while( (c=getchar()) != ‘ ’ ) while(c != ‘ ’ ) { { putchar( c ) ; putchar( c ) ; } c = getchar() ; } 4
  5. caps Program  Example: – Change uppercase to lowercase or lowercase to uppercase #include <stdio.h> int main(void) { while (( c = getchar() ) != ‘n’) { if( ‘A’ <= c && c <= ‘Z’ ) putchar( c + (‘a’-’A’) ) ; else if( ‘a’ <= c && c <= ‘z’ ) ; putchar( c - (‘a’-’A’) ) ; else putchar( c ) ; } return 0; } 5
  6. The Macros in ctype.h  ctype.h defines macros of character types. Character macros Macro Nonzero (true) is returned if isalpha(c) c is a letter isupper(c) c is an uppercase letter islower(c) c is a lowercase letter isdigit(c) c is a digit isalnum(c) c is a letter or digit isxdigit(c) c is a hexadecimal digit isspace(c) c is a white space character ispunct(c) c is a punctuation character isprint(c) c is a printable charcter isgraph(c) c is a printable, but not a space iscntrl(c) c is a control character isascii(c) c is an ASCII code 6
  7. The Macros in ctype.h  toupper() and tolower() functions Character macros and functions Function or macro Effect toupper(c) Changes c from lowercase to uppercase tolower(c) Changes c from uppercase to lowercase toascii(c) Changes c to ASCII code [Ex] int tolower(int c); /* Return lowercase if ‘c’ is uppercase */ int toupper(int c); /* Return uppercase if ‘c’ is lowercase */ [Ex] #define _tolower(c) ( (c) + ‘a’ – ‘A’ ) /* Define a function using #define */ 7
  8. caps Program  Example: – Changing uppercase to lowercase or lowercase to uppercase #include <stdio.h> #include <ctype.h> int main(void) { while (( c = getchar() ) != ‘n’) { if( isupper(c) ) putchar( tolower(c) ) ; else if( islower(c) ) ; putchar( toupper(c) ) ; else putchar( c ) ; } return 0; } 8
Publicité