getchar Function in C
Last Updated :
01 Jun, 2023
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.
- It is defined inside the <stdio.h> header file.
- Just like getchar, there is also a function called putchar that prints only one character to the standard output stream.
Syntax of getchar() in C
int getchar(void);
getchar() function does not take any parameters.
Return Value
- The input from the standard input is read as an unsigned char and then it is typecast and returned as an integer value(int).
- EOF is returned in two cases:
- When the file end is reached
- When there is an error during the execution
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
#include <stdio.h>
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
#include <stdio.h>
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
#include <stdio.h>
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
#include <ctype.h>
#include <stdio.h>
int main()
{
int ch, i = 0;
char str[150];
printf ( "Enter the characters\n" );
do {
ch = getchar ();
str[i] = ch;
i++;
} 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
Share your thoughts in the comments
Please Login to comment...