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!
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!
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
Whilst it might work for you, it won't work for meCode:fflush( stdin );
A better fix (for fix it most surely is) is
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.Code:while ( getchar() != '\n' ) ; /* munch chars until newline */
You shouldn´t use gets() !!
Use fgets() to prevent overflows!
klausi
When I close my eyes nobody can see me...