getchar And putchar Function

At the character level, getchar() reads one character at a time from stdin, while putchar() writes one character at a time to stdout.

#include

main()  {   int i;   int ch;

for( i = 1; i<= 5; ++i ) {   ch = getchar();   putchar(ch);   }  }

Program Output :

AACCddEEtt

If there is an error then EOF (end of file) is returned instead. It is therefore usual to compare this value against EOF before using it. If the return value is stored in a char, it will never be equal to EOF, so error conditions will not be handled correctly.

#include < stdio.h>

void main() {   int i, nc;

nc = 0;   i = getchar();   while (i != EOF)   {  nc = nc + 1;  i = getchar();   }   printf("Number of characters in file = %dn", nc); }

Note that getchar() gets a single character from the keyboard, and putchar() writes a single character to the console screen.

Post Comment
Login to post comments