I am confused about getchar()
's role in the following code. I mean I know it's helping me see the output window which will only be closed when I press the Enter key.
So getchar()
is basically waiting for me to press enter and then reads a single character.
What is that single character this function is reading? I did not press any key from the keyboard for it to read.
Now when it's not reading anything, why does it not give an error saying "hey, you didn't enter anything for me to read"?
#include <stdio.h>
int main()
{
printf( "blah \n" );
getchar();
return 0;
}
As we can see, when we execute the above program, it takes a single character or group of characters using the scanf() library function instead of the getchar() function.
Definition. scanf is a C function to read input from the standard input until encountering whitespace, newline or EOF while getchar is a C function to read a character only from the standard input stream(stdin), which is the keyboard. Thus, this is the main difference between scanf and getchar.
putchar() function is a file handling function in C programming language which is used to write a character on standard output/screen. getchar() function is used to get/read a character from keyboard input.
Originally Answered: What is the problem with getchar()? Getchar() is one of the function which is used to take input from the user. But at a time it can take only one character.. if the user give more than one character also,it reads only one character.
That's because getchar() is a blocking function.
You should read about blocking functions, which basically make the process wait for something to happen.
The implementation of this waiting behavior depends on the function, but usually it's a loop that waits for some event to happen.
For the case of the getchar()
function, this probably is implemented as a loop that constantly reads a file (stdin for this case) and checks weather the file is modified. If the file is modified, the loop behaves by doing something else.
The getchar()
function will simply wait until it receives a character, holding the program up until it does.
A character is sent when you hit the enter key; under a Windows OS, it will send a carriage return (CR) and a line-feed (LF).
See this CodingHorror post for a nicely put explanation.
(...the explanation of the CR+LF part, not the getchar()
blocking part)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With