about scanf and gets

This is a discussion on about scanf and gets within the C Programming forums, part of the General Programming Boards category; Can u mix-use 'scanf' and 'gets' in the same c-program? I heard that u cannot mix-use 'scanf' and 'fgets' in ...

  1. #1
    Unregistered
    Guest

    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,546
    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
    Code:
    fflush( stdin );
    Whilst it might work for you, it won't work for me

    A better fix (for fix it most surely is) is
    Code:
    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
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,493

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

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

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21