Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about getchar() function

Tags:

c

getchar

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;
}
like image 748
Serenity Avatar asked Mar 09 '10 10:03

Serenity


People also ask

What can I use instead of Getchar in C?

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.

What are the differences between getchar and scanf?

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.

What is the difference between getchar and putchar function?

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.

What is the problem with Getchar?

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.


2 Answers

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.

like image 106
Luca Matteis Avatar answered Oct 11 '22 19:10

Luca Matteis


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)

like image 34
detly Avatar answered Oct 11 '22 21:10

detly