C - Read characters with getchar()

Introduction

The following code uses the getchar() function.

This function reads a character from standard input.

Demo

#include <stdio.h> 

int main() //from   www.  ja v  a2  s  .  c  o m
{ 
     int c; 

     printf("I'm waiting for a character: "); 
     c = getchar(); 
     printf("I waited for the '%c' character.\n",c); 
     return(0); 
}

Result

The code reads a character from standard input by using the getchar() function.

The character is returned from getchar() and stored in the c integer variable.

Then it displays the character stored in c.

The printf() function uses the %c placeholder to display single characters.

The getchar() function is defined this way:

int getchar(void); 

The function has no arguments.

And the getchar() function requires the stdio.h header file to be included with your source code.

getchar() returns an integer value, not a char variable.

Related Topic