From the course: Complete Guide to C Programming Foundations

Using single character I/O

- [Narrator] A basic form of input and output involves characters. For the C language, characters come from the standard input device, usually the keyboard, and they're sent to the standard output device, the terminal window or display. Here the "putchar" function sends five single character constants to standard output, one statement after the other. The final "putchar" function sends a new line, which helps make the display readable. Hello. The "getchar" function fetches a character from standard input as shown in this exercise file. The function requires no arguments and returns an integer value. Therefore, at line five, variable "ch" is defined as an integer, not a character variable. The character is read from standard input at line eight and then output by the "printf" statement at line nine. I'll type a "K" and there's the "K." C uses stream input, which isn't interactive, like most programs you're familiar with. To prove it, I can update the code to fetch a second character. First, add the second integer variable, (keyboard clicks) duplicate these lines and modify the "printf" statement. (keyboard clicks) Just from reading the code, you might assume that one character is read, pause, and then the other character is read. Let's see if that's true. And I'm going to type "A" enter. Hmm. What you see in the output is, in fact, what I typed. "A" and then enter. Enter is the second character. The enter key press is read from the stream and supplied for variable "ch2." So run the code again. Now at the prompt, I'm going to type "A B" and then enter. You see both characters now. This is how stream input works and you must be mindful of it as you code basic input output in C. Finally, I want to address why the "getchar" function returns an integer and not a character value. This exercise file is what I call a typewriter program. It accepts standard input and then turns around and sends the same character to standard output, "getchar" and "putchar." At line 10, the character input is compared with the EOF, end of file, constant, which is an integer. Run the code. Now there's no prompt. The program is running right now and I can type some text, (keyboard clicks) press enter, and the buffer is flushed and then the characters are output. To end the program, you must press the "EOF" character, which in Unix is Control D, and the program is done. If you run this under Windows, press Control Z, which is that operating system's end of file character. What I'm trying to explain is why "getchar" and "putchar" work with integer values and not character values. The EOF constant is an integer. You cannot read this value if you use a character variable type. This explains why "A," in this code and all variables you would use with "getchar" and "putchar" must be integers and not characters.

Contents