Showing posts with label Use of getchar function. Show all posts
Showing posts with label Use of getchar function. Show all posts

Use of getchar function

Program 10) This program shows the use of getchar function in an interactive enviroment.

The program displays a question of YES/NO type to the user and reads the user's response in a single character (Y or N). If the response is Y or y, it outputs the message 
                       My name is BUSY BEE
otherwise, outputs
                      You are good for nothing

                              PROGRAM
#include <stdio.h>
main( )
 {
       char answer ;
       printf("Would you like to know my name?\n") ;

       printf("Type Y for YES and N for NO: ") ;

       answer = getchar( ) ; 
       if(answer == 'Y' || answer == 'Y')
          printf("\n\nyou are good for nothing\n") ;
       getch( ) ;
 }

Output:           Would you like to know my name?
                       Type Y for YES and N for NO:  Y
                     
                        My name is Busy Bee
                   
                       Would you like know my name
                       Type Y for YES and N for NO:N         
                       You are good for nothing
  
Use of getchar function to read a character fromKeyboad 

                                      WARNING  
The getchar( ) function accepts any character keyed in. This includes RETURN and TAB. This means when we enter single character input, the newline character is waiting in the input quenue after getchar( ) returns. This could create problems when we use getchar( ) in a loop interactively. A dummy getchar( ) may be used to 'eat' the unwanted new line character. We can also use the fflush function to flush out the unwanted characters.