The function getchar () read and write (display) single character. The function getchar () reads and returns the next character from standard input stream. The standard input is from keyboard. If the function encounters end-of-file character, it returns EOF. Also, if an error occurs in reading, then also the function returns EOF. The prototype of the function is
int getchar (void); /*function type is int and no arguments (void).*/
It may be used as shown below.
char ch ;
ch= getchar();
The function reads single character at a time, however, it may be used to read a string with the help of a loop, i.e., read the string character by character. Since the function has access to single character it is useful in manipulating the characters of a string, i.e., altering a character in a string or for counting all characters or for counting the occurrence of particular character in a string. Illustrates use of getchar ().
#include <stdio.h>
int main(void)
{
int a, b;
char ch;
printf("Choice:\n");
printf("Add, Subtract, Multiply, or Divide?\n");
printf("Enter first letter: ");
ch = getchar();
printf("\n");
printf("Enter a: ");
scanf("%d", &a);
printf("Enter b: ");
scanf("%d", &b);
if(ch=='A') printf("%d", a+b);
if(ch=='S') printf("%d", a-b);
if(ch=='M') printf("%d", a*b);
if(ch=='D' && b!=0) printf("%d", a/b);
return 0;
}