Thread: How to flush the buffer

  1. #1
    Unregistered
    Guest

    How to flush the buffer

    Hai guys,

    I have a problem in the program,


    Code:
    int main()
    {
    	char option='y';
    while( option == 'y')
    {
    	/* do somthing */
    	printf("Want to continue [y|n]");
    	scanf("%c",&option);
    }
    
    }
    it works very well in first time , when i give the input 'y'. But it come out of the loop when i give the same char 'y' in the second time. what is the error in this program. i am working in linux OS. Help me.

  2. #2
    Registered User
    Join Date
    Apr 2002
    Posts
    26
    here u go!

    #include <stdio.h>
    int main()
    {
    char option='y';char trash;
    while( option == 'y')
    {
    /* do somthing */
    printf("Want to continue [y|n]");
    scanf("%c%c",&option,&trash);
    }

    }

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Code:
    while (getchar() != '\n');
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Unregistered
    Guest

    ha ha

    scanf("%c%c",&option,&trash)

    cool... it is kinda funny to see "trash"
    'cause i used to have this lousy problem when
    i was new

  5. #5
    Registered User moonwalker's Avatar
    Join Date
    Jul 2002
    Posts
    282
    here's a nifty function that does what you want

    PHP Code:
    char playagain()        //asks if he/she wants to play again
    {
        
    char yesorno;
        do 
        {
            
    printf("Do you want to play again? (y/n): ");
            
    scanf("%c", &yesorno);
            
    fflush(stdin);
        } while (
    yesorno != 'y' && yesorno != 'Y' && yesorno != 'n' && yesorno != 'N');
        return 
    yesorno;


  6. #6
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    >> fflush(stdin);

    Oh boy someone's in for it!!

  7. #7
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Good grief, not the fflush(stdin) conversation AGAIN!

    Don't do it, don't teach others to do it. It's just plain wrong.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  2. writing a pack-style function, any advices?
    By isaac_s in forum C Programming
    Replies: 10
    Last Post: 07-08-2006, 08:09 PM
  3. Flush Input Buffer
    By zx-1 in forum C Programming
    Replies: 41
    Last Post: 10-29-2005, 08:58 AM
  4. buffer contents swapping
    By daluu in forum C++ Programming
    Replies: 7
    Last Post: 10-14-2004, 02:34 PM
  5. Console Screen Buffer
    By GaPe in forum Windows Programming
    Replies: 0
    Last Post: 02-06-2003, 05:15 AM