getchar Function in C (original) (raw)

Last Updated : 30 May, 2026

The getchar() function in C is a standard library function used to read a single character from the standard input device (keyboard). It is commonly used for simple character-based input operations.

#include <stdio.h>

int main() { char ch;

printf("Enter a character: ");
ch = getchar();

printf("You entered: %c", ch);

return 0;

}

`

Output

Enter a character: You entered: �

Syntax

int getchar(void);

getchar() function does not take any parameters.

Return Value

Examples of C getchar Function

The following C programs demonstrate the use of getchar() function

**Example 1: Read a single character using getchar() function.

C `

#include <stdio.h>

// Driver code int main() { int character; character = getchar();

printf("The entered character is : %c", character);
return 0;

}

`

**Input

f

**Output

The entered character is : f

**Example 2: Program to implement putchar to print the character entered by the user:

C `

#include <stdio.h>

// Driver code int main() { int character; printf("Enter any random character between a-z: "); character = getchar();

printf("The entered character is : ");
putchar(character);
return 0;

}

`

**Input

Enter any random character between a-z: k

**Output

The entered character is : k

**Example 3: Reading multiple characters using getchar()

C `

#include <stdio.h>

// Driver code int main() { int s = 13; int x; while (s--) { x = getchar(); putchar(x); } return 0; }

`

**Input

geeksforgeeks

**Output

geeksforgeeks

**Example 4: Read sentences using getchar() function and do-while loop.

C `

#include <stdio.h> // Driver code int main() { int ch, i = 0; char str[150];

printf("Enter the characters\n"); 

do { 
    // Read character from input 
    ch = getchar(); 
    // Store character in array 
    str[i] = ch; 
    // Increment index 
    i++; 
    
} while (i < 149 && ch != '\n'); 
// Add null character at end 
str[i] = '\0'; 

printf("Entered characters are %s", str); 

return 0; 

}

`

**Input

Enter the characters Welcome to GeeksforGeeks

**Output

Entered characters are Welcome to GeeksforGeeks