by Dinesh Thakur Category: C Programming (Pratical)

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("Add, Subtract, Multiply, or Divide?\n");
  printf("Enter first letter: ");
  ch = getchar();
  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;
 Write a Program For getchar() to Read user Choices

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.