Using the getc() Function
The getc() function reads the next character from a file stream, and returns the character as an integer.
The syntax for the getc() function is
#include <stdio.h>
int getc(FILE *stream);
Here FILE *stream declares a file stream (that is, a variable). The function returns the numeric value of the character read. If an end-of-file or error occurs, the function returns EOF.
At this moment, don't worry about the FILE structure. More details about it are introduced in Hours 21, "Disk File Input and Output: Part I," and 22, "Disk File Input and Output: Part II." In this section, the standard input stdin is used as the file stream specified by FILE *stream.
NOTE
Defined in the header file stdio.h, EOF is a constant. EOF stands for end-of-file. Usually, the value of EOF is -1. But keep using EOF, instead of -1, if you need an end-of-file indicator, in case a compiler uses a different value.
Listing 5.1 shows an example that reads a character typed in by the user from the keyboard and then displays the character on the screen.
TYPE
Listing 5.1. Reading in a character entered by the user.
1: /* 05L01.c: Reading input by calling getc() */
2: #include <stdio.h>
3:
4: main()
5: {
6: int ch;
7:
8: printf("Please type in one character:\n");
9: ch = getc( stdin );
10: printf("The character you just entered is: %c\n", ch);
11: return 0;
12: }
The following is the output displayed on the screen after I run the executable file, 05L01.exe, enter the character H, and press the Enter key:
C:\app> 05L01
Please type in one character:
H
The character you just entered is: H
C:\app>
OUTPUT
You see in line 2 of Listing 5.1 that the header file stdio.h is included for both the getc() and printf() functions used in the program. Lines 4_12 give the name and body of the main() function.
ANALYSIS
In line 6, an integer variable, ch, is declared; it is assigned the return value from the getc() function later in line 9. Line 8 prints out a piece of message that asks the user to enter one character from the keyboard. As I mentioned earlier in this lesson, the printf() function in line 8 uses the default standard output stdout to display messages on the screen.
In line 9, the standard input stdin is passed to the getc() function, which indicates that the file stream is from the keyboard. After the user types in a character, the getc() function returns the numeric value (that is, an integer) of the character. You see that, in line 9, the numeric value is assigned to the integer variable ch.
Then, in line 10, the character entered by the user is displayed on the screen with the help of printf(). Note that the character format specifier (%c) is used within the printf() function in line 10. (Exercise 1 in this lesson asks you to use %d in a program to print out the numeric value of a character entered by the user.)