About getchar() in C

getchar() is a simple but powerful function from the C standard library that allows you to read characters from standard input.

It is defined in the header file <stdio.h> and has the following prototype:

int getchar(void);

The int return type is used because getchar() returns a character from the input stream as an integer. This allows it to handle all possible character values, as well as special values like EOF (end of file). Because in C, characters (char) are represented as integer values corresponding to their encoding in the ASCII table. For example, the letter 'A' has an ASCII code of 65, and 'a' has 97. And by returning the value as an int, getchar() can handle not only all ASCII characters but also special values like EOF.

EOF (end-of-file) is a special value indicating that the input stream has ended. It is usually represented as -1. If getchar() returned a char type, it would be impossible to distinguish EOF from valid characters, as char ranges from -128 to 127 or from 0 to 255 (depending on the implementation). Using int avoids this issue, as EOF typically has a value that is outside the range of ASCII characters.

Also, calling getchar() blocks the program's execution until a character is entered and the Enter key is pressed. This is convenient for interactive data input.

Here’s a straightforward example of using getchar() with two conditions for clarity:

#include <stdio.h>

int main() {
    int c;

    printf("Enter text (to finish, enter Ctrl+D or 'd'):\n");
    while ((c = getchar()) != 'd' && c != EOF) {
        putchar(c);
    }

    printf("\nProgram terminated.\n");
    return 0;
}

In this example, getchar() is used to read a character from standard input. This character is stored in the variable c. The while loop continues as long as the entered character is not 'd' and not EOF. This allows the program to terminate when the user inputs d or presses Ctrl+D on macOS. The entered character is output back to the screen using putchar(c).

To fully understand how getchar() works, try entering single characters as well as whole words and sentences. Input to getchar() is buffered until you press the Enter key. This means that getchar() does not receive a character immediately after it is pressed but only after the line of input is complete. So, if you enter kghdkeh, the program will output only kgh because it will stop at d according to the condition.

Published on August 14, 2024 by Yeldar Kudaibergenov