Results 1 to 5 of 5

Thread: Mysterious Program

  1. #1
    Join Date
    Dec 2011
    Beans
    46

    Question Mysterious Program

    Sir,
    Please consider the below C code.

    #include<stdio.h>
    void main()
    {
    char c1,c2;
    do
    {
    printf("\nEnter a character");
    scanf("%c",&c1);
    printf("\nDo you want to continue?yes(y),no(n)\n");
    scanf("%c",&c2);
    }while(c2=='y');
    }



    The second scanf is not working !!!! I don't know why this happens.
    The program just exits after the printf statement.
    Please explain why this happens..
    I have used gcc for compiling the program

  2. #2
    Join Date
    May 2006
    Beans
    1,787

    Re: Mysterious Program

    Quote Originally Posted by achuth View Post
    Sir,
    Please consider the below C code.

    #include<stdio.h>
    void main()
    {
    char c1,c2;
    do
    {
    printf("\nEnter a character");
    scanf("%c",&c1);
    printf("\nDo you want to continue?yes(y),no(n)\n");
    scanf("%c",&c2);
    }while(c2=='y');
    }



    The second scanf is not working !!!! I don't know why this happens.
    The program just exits after the printf statement.
    Please explain why this happens..
    I have used gcc for compiling the program
    Don't use scanf. Read one line with fgets and then parse it with sscanf.

  3. #3
    Join Date
    Aug 2011
    Location
    47°9′S 126°43W
    Beans
    2,165
    Distro
    Kubuntu 14.04 Trusty Tahr

    Re: Mysterious Program

    Quote Originally Posted by achuth View Post
    Sir,
    Please consider the below C code.

    #include<stdio.h>
    void main()
    {
    char c1,c2;
    do
    {
    printf("\nEnter a character");
    scanf("%c",&c1);
    printf("\nDo you want to continue?yes(y),no(n)\n");
    scanf("%c",&c2);
    }while(c2=='y');
    }



    The second scanf is not working !!!! I don't know why this happens.
    The program just exits after the printf statement.
    Please explain why this happens..
    I have used gcc for compiling the program
    The second scanf() is working... what it gets is the LF you entered at the first prompt (because you had to strike the Enter key... so reallyt entered "a\n", for instance). Your code has to consume that character... as well as anything you enter at the first prompt before hitting Enter ("yyyyyyyyyynnnnn[Enter]")

  4. #4
    Join Date
    Dec 2011
    Beans
    46

    Re: Mysterious Program

    ofnuts helped me.
    Thanks.
    Thread ends here.

  5. #5
    Join Date
    May 2006
    Beans
    1,787

    Re: Mysterious Program

    Quote Originally Posted by achuth View Post
    ofnuts helped me.
    Thanks.
    Thread ends here.
    Then you can mark it "solved".

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •