It has already been recommended that you not use scanf
. If you feel you must use scanf
, you really should be checking the return value to determine if an input error occurred prior to the conversion.
It has also been noted that you should not be flushing stdin
via fflush
as it invokes undefined behavior. If you feel that you must flush stdin
, you may want to refer to the answers to this question.
If an invalid value such as "1,234" is entered, scanf
will accept the '1' and the ",234/n" will be left in the input stream. Since fflush(stdin)
is not guaranteed to work, subsequent calls to scanf
will keep rejecting the same ',' over and over again, never making any progress. If the return value is checked for zero (indicating an early matching failure), this infinite loop can be avoided. It is also necessary to remove the invalid character(s) from the input stream prior to another call to scanf
.
See scanf() causing infinite loop as well.