getchar() function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mahiapkum
    New Member
    • Mar 2007
    • 35

    getchar() function

    Hello,
    I have a code which uses getchar().
    [CODE=c]#include<stdio. h>
    int main()
    {
    char ch;
    ch = getchar();
    if(ch == 'Y')
    {
    printf("Beautif ul World\n");
    }
    else
    {
    printf("Cruel World\n");
    }
    ch = getchar();
    if(ch == 'N')
    {
    printf("Second getchar\n");
    }
    else
    {
    printf("Second getchar else part\n");
    }
    return 0;
    }[/CODE]


    and the o/p is
    Beautiful World
    Second getchar else part

    the second getchar() is not waiting to enter the character from the user....
    Last edited by Ganon11; Oct 25 '07, 01:45 PM. Reason: Please use the [CODE] tags provided.
  • mattmao
    New Member
    • Aug 2007
    • 121

    #2
    Hi, you need to clear keyboard buffer before asking the user to inter the second char, for example:

    Code:
    #include<stdio.h>
    int main()
    {
    char ch;
    ch = getchar();
    if(ch == 'Y')
    {
    printf("Beautiful World\n");
    }
    else
    {
    printf("Cruel World\n");
    }
    while(getchar()!='\n');
    ch = getchar();
    if(ch == 'N')
    {
    printf("Second getchar\n");
    }
    else
    {
    printf("Second getchar else part\n");
    }
    return 0;
    }

    Note this line of code:
    while(getchar() !='\n');

    It does this job for you. Now I hope this code works as you intended to.

    Comment

    • mahiapkum
      New Member
      • Mar 2007
      • 35

      #3
      could u pls explain the line "while(getchar( )!='\n');" the code is working fine but i didnt understand how the above line of code works.

      Originally posted by mattmao
      Hi, you need to clear keyboard buffer before asking the user to inter the second char, for example:

      Code:
      #include<stdio.h>
      int main()
      {
      char ch;
      ch = getchar();
      if(ch == 'Y')
      {
      printf("Beautiful World\n");
      }
      else
      {
      printf("Cruel World\n");
      }
      while(getchar()!='\n');
      ch = getchar();
      if(ch == 'N')
      {
      printf("Second getchar\n");
      }
      else
      {
      printf("Second getchar else part\n");
      }
      return 0;
      }

      Note this line of code:
      while(getchar() !='\n');

      It does this job for you. Now I hope this code works as you intended to.

      Comment

      • rhitam30111985
        New Member
        • Aug 2007
        • 112

        #4
        Originally posted by mahiapkum
        could u pls explain the line "while(getchar( )!='\n');" the code is working fine but i didnt understand how the above line of code works.
        program wont get out of the while loop until user presses the 'enter' key which is nothing but the newline character('\n') ..once press enter.. it will take the next character.

        Comment

        Working...