Thread: gets() problem

  1. #1
    1337
    Join Date
    Jul 2008
    Posts
    135

    gets() problem

    When i used a few gets() to obtain strings from the user, My programme will not run properly. At some point of gets(), it didn't pause whereas it just continues running without waiting for the user input.

    So i tried using scanf() with fflush().. it solved the problem. How ever this method is not recommended, please tell me what i should do.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    No, gets() IS THE PROBLEM!
    Cprogramming.com FAQ > Why gets() is bad / Buffer Overflows

    Use fgets() to read every single bit of your input - no scanf, no getchar, and DEFINITELY NO gets().
    When the line of input is in a buffer, then you can parse it however you want, say using sscanf if you're feeling lazy.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Post up an example showing the problem, along with the input that caused it, and we'll show you the fix.

    There are two probable reasons for this:

    1) gets() is being over-filled at some point with undefined results
    2) gets() is encountering left over char's (probably newlines), in the keyboard buffer, and accepting those as input for one or more of your variables.

    Either way, we can fix it.

    fflush() on standard input is very unreliable. It works very well on output streams, but not on input streams.

    #2 is by far the most common problem on this forum.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help understanding a problem
    By dnguyen1022 in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2009, 04:21 PM
  2. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  3. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  4. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  5. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM