Thread: Scanf behavior

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    8

    Question Scanf behavior

    Hi all
    I found this weird problem which I hadn't seen before. I was working on Cygwin (the problem later replicated on a real linux box as well). I was writing a program where I needed to do something like:

    Code:
    while(ch == 'y')
    {
      x = myfunc();
      //do something ...
      printf("\n Enter y to insert again:");
      scanf("%c",&ch); // I tried using getchar() and getch() also.
    }
    Now my problem is that this loops only once whatever input I give. The first time it loops correctly, the 2nd time it gets into the lopp and exits after the printf. I tried using fflush() but that didn't help either. Am I doing something really stupid?

    Thanks

  2. #2
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    I am guessing there is something left in the buffer that scanf reads in the second time around. Have a look at the following FAQs:

    FAQ > Explanations of... > Why fflush(stdin) is wrong

    FAQ > How do I... (Level 2) > Flush the input buffer

    FAQ > How do I... (Level 1) > Get a line of text from the user/keyboard (C)

    You might also want to check out some of Dave Sinkula's articles beginning with this one.

    That should get you started anyway. Generally what it comes down to is that you end up rolling your own function, incorporating some of the library functions, to suit your particular needs.

  3. #3
    Registered User
    Join Date
    Aug 2006
    Posts
    8
    Thanks
    Hmm, all this while I hadn't known this. I never saw scanf behaving like that before. Is it because of the while loop?

  4. #4
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    >>Is it because of the while loop?

    Yes, kind of, more specifically because the newline left in the input buffer is a
    char. Read this thread where I descibed what's happening in detail.
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with a basic scanf procedure.
    By killpoppop in forum C Programming
    Replies: 9
    Last Post: 11-03-2008, 04:39 PM
  2. Strange scanf behavior
    By exvor in forum C Programming
    Replies: 7
    Last Post: 07-25-2005, 11:54 AM
  3. Replies: 2
    Last Post: 02-20-2005, 01:48 PM
  4. scanf issue
    By fkheng in forum C Programming
    Replies: 6
    Last Post: 06-20-2003, 07:28 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM