C - Write program to return the first character from stream and swallow the rest characters until \n

Requirements

Create a function that returns the first character in the stream and then swallows the rest of the characters until the \n is encountered.

Demo

#include <stdio.h>

char getch(void);

int main()/*from   www.j  a v  a2s . c  om*/
{
    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);
}

Result

Related Exercise