Thread: about scanf and gets

  1. #1

    Question about scanf and gets

    Can u mix-use 'scanf' and 'gets' in the same c-program?

    I heard that u cannot mix-use 'scanf' and 'fgets' in the same program, just wondering why?

    Great Appriciation if anyone can answer me those questions!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    It's not that you can't, it's more that you shouldn't

    The problem
    scanf uses the minimum number of characters from the input stream. This typically means that the \n character is left until next time. This isn't a problem if the call is another scanf call.

    However, \n is exactly what fgets (and the icky gets) functions expect at end of input, so these calls following scanf typically seem to fail for no reason at all
    "help, my program is skipping input" is the usual cry of the newbie

    The INCORRECT way of solving the problem is
    fflush( stdin );
    Whilst it might work for you, it won't work for me

    A better fix (for fix it most surely is) is
    while ( getchar() != '\n' ) ;  /* munch chars until newline */
    The problem all but goes away if you stick to always using fgets for reading input, then using sscanf (or whatever else you like) to interpret the contents of the buffer which fgets fills in for you.

  3. #3

  4. #4
    Registered User
    Join Date
    Oct 2001
    You shouldn´t use gets() !!
    Use fgets() to prevent overflows!

    When I close my eyes nobody can see me...

Popular pages Recent additions subscribe to a feed