getchar() and putchar() in C

In this article, we would discuss the two standard library functions i.e. getchar() and putchar() in C. getchar() helps us read the next input character whereas, putchar() writes a character. We emphasize that, both these functions read and write a character every time they are called.

We will understand these functions with the help of couple of programs. The programs are –

Program 1 – for getchar() and putchar() in C
#include <stdio.h>
/* Output is the copy of input */
int main(void)
{
  int a;
  printf("Enter a text: ");
  a = getchar();
  while (a != EOF) 
    {
      putchar(a);
      printf("\n");
      a = getchar();
    }
}

Program 1 explained –

#include <stdio.h>

A directive to preprocessor to include stdio.h

a = getchar();

To get the first character

while (a != EOF)

We have used a symbolic constant EOF. EOF is End of File. Trigger an EOF response through Ctrl+D, once we decide to no longer provide any further input. A while loop to ensure it keeps getting the input till we trigger an EOF response. Anything else we provide as an input would simply copy and print as output.

putchar(a);

To print the character –

printf("\n");

This was just to remind you that it always reads/writes one character at a time.

Program 2 – for getchar() and putchar() in C

This time we would replace symbolic constant EOF with #. We keep everything as it is from Program 1.

#include <stdio.h>
/* Output is the copy of input */
int main(void)
{
   int a;
   printf("Enter text or # to exit: ");
   a = getchar();
   while (a != '#') 
     {
        putchar(a);
        printf("\n");
        a = getchar();
     }
}

Provide a text as an input. This one also copies the input to provide us the desired output. But, this time around, we can trigger an End of file response through #. In earlier program i.e. Program 1 we used Ctrl+D. Press # this time to get the desired outcome. Everything else is the same and already explained in Program 1 section.

In conclusion, we have discussed getchar() and putchar() in C with the help of couple of programs.

Additional Info –

We compile the code through GNU Compiler Collection (GCC)

gcc -o get-put get-put.c

If there are any issues (i.e. errors/warnings) with code then, it will notified as this stage. If it returns with nothing then, proceed with the following –

./get-put