Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is getchar in C?

Hassaan Waqar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The getchar function is part of the <stdio.h> header file in C. It is used when single character input is required from the user. The function reads the input as an unsigned char; then it casts and returns as an int or an EOF.

EOF is returned if the end of file is reached or an error is encountered.

getchar casts to int to allow the representation of EOF, which cannot be represented using a char.

The illustration below shows how getchar works:

How does getchar work?

Declaration

The getchar function is declared as follows:

int getchar(void)

The getchar function takes no parameter.

Example

The code snippet belwo shows how getchar can be used:

Input your character using the STDIN option, then press Run.

#include<stdio.h> // Including header file
int main(){
int myChar; // creating a variable to store the input
myChar = getchar(); // use getchar to fetch input
printf("You entered: %c", myChar); // print input on screen
return 0;
}

Enter the input below

The output above shows a single character printed on-screen. In the case that multiple characters are input, we will only pick the first character.

There is a slight difference betweengetchar and getc. getchar only takes a character from standard input, whereas getc can fetch a character from any input stream, e.g., files.

RELATED TAGS

c

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring