Solution for Exercise 13-19

ex1319

#include <stdio.h>

char getch(void);

int main()
{
    char first,second;

    printf("Type your first initial: ");
    first = getch();
    printf("Type your second initial: ");
    second = getch();
    printf("Your initials are '%c' and '%c'\n",first,second);
    return(0);
}

char getch(void)
{
    char ch;

    ch = getchar();
    while(getchar()!='\n')
        ;
    return(ch);
}

Notes

* While this code works for keyboard input, it could have a serious problem if input were redirected from a file and that file ended before the second initial were input. Technically, the end-of-file or EOF marker would be encountered and the program would sit and wait for input that would never come. To fix that predicament, you need to test whether the getchar() function encountered the EOF. Further, you have to clear the error condition generated when the EOF is read. Here is the proper code for the getch() function:

char getch(void)
{
    char ch;
    int r;

    ch = getchar();
    do
        r = getchar();
    while( r != EOF && r != '\n' );
    clearerr(stdin);
    return(ch);
}

* The final function, clearerr(), handles the error that occurs when the EOF is read from the input stream. stdin is the standard input device.

* I'd like to acknowledge reader JSW for inspiring the above code.