C getchar() Usage and Examples

The getchar() function is used to grab character by character inputs from the standard input stream. getchar() is special in that it takes a void as its argument, i.e. nothing and it returns the next character from standard input. This can be used for basic input into any c program.

I will outline a basic example here.

How To Use getchar()

The getchar() function, as I mentioned above is quite basic, I will show you how to read input from standard in and print it back out to the terminal as standard out.

#include <stdio.h>
 
int main()
{
        char c;
        for(;;){
                c=getchar();
                if(c == 'q') // Compare input to 'q' character
                        break;
                fprintf(stdout, "%c\n", c);
        }
        return 0;
}

To compile this program:

erik@debian:~/getchar_ex$ gcc -o getchar_test getchar_test.c

Using this function:

erik@debian:~/getchar_ex$ ./getchar_test
a
a
 
 
b
b
 
 
c
c
 
 
q
q
erik@debian:~/getchar_ex$

As you can see, we read in each character then the process prints it back out. Nothing to it really.

getchar() Return Values

getchar() will return an unsigned char that is internally cast to an int. If there is an error or end of line the function will return an EOF (end of file).