Solution for Exercise 13-18

ex1318

#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);
}

Output

Type your first initial: D
Type your second initial: G
Your initials are 'D' and 'G'

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 was generated. 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 this predicament, you must 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 non-exploitable code for the getch() function:

int getch(void)
{
    int ch,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.