Open In App

getchar Function in C

C getchar is a standard library function that takes a single input character from standard input. The major difference between getchar and getc is that getc can take input from any no of input streams but getchar can take input from a single standard input stream.

Syntax of getchar() in C

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.

Below is the C program to implement getchar() function to read a single character:






// C program to implement getchar()
// function to read single character
#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: Implementing Putchar

Below is the C program to implement putchar to print the character entered by the user:




// C program to implement putchar
// to print the character entered
// by user
#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()

Below is the C program to read multiple characters using getchar():




// C program to read multiple characters
// using getchar():
#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.

Below is the C program to read characters using a do-while loop:




// C program to read characters using
// getchar() and do-while loop
#include <ctype.h>
#include <stdio.h>
 
// Driver code
int main()
{
    int ch, i = 0;
    char str[150];
    printf("Enter the characters\n");
 
    do {
        // takes character, number, etc
        // from the user
        ch = getchar();
 
        // store the ch into str[i]
        str[i] = ch;
 
        // increment loop by 1
        i++;
 
        // ch is not equal to '\n'
    } while (ch != '\n');
 
    printf("Entered characters are %s ", str);
    return 0;
}

Input

Enter the characters
Welcome to GeeksforGeeks

Output

Entered characters are Welcome to GeeksforGeeks

Article Tags :