The getchar Function (Continued)

Next we use the getchar function again, once for its usual purpose, and once again to soak up a carriage return. This may seem strange, given that we have just made use of a getchar. Here is how it works. The first getchar retrieves a single character from the user. However, nothing at all is fed to getchar until the user has pressed ENTER. This additional ENTER is what needs to be soaked up by the second getchar.

Alternatively, we could have asked the user to actually press ENTER straight away, then only a single getchar would have been required. However, in this instance we wanted to demonstrate how getchar can be used to retrieve a character from the user.

Whichever character the user inputs, needs to be stored somewhere. The place to do this is a variable of type char. This is what keypressed is defined to be, on the second line of our program proper. Now an equals sign is used to set keypressed equal to the character which getchar obtains from the user.

This character is repeated back to the user in the next printf bar one. Here of course, a %c is used in the format string to indicate that the contents of a variable of type char is to be displayed.