且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

scanf在while循环中

更新时间:2021-08-23 21:29:06

已经建议您

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.

还应注意,您不应通过fflush刷新stdin,因为它会调用未定义的行为.如果您认为必须刷新stdin,则可能要参考

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.

如果输入了无效值,例如"1,234" ,则scanf将接受'1',234/n" 将保留在输入流中.由于不能保证fflush(stdin)正常工作,因此对scanf的后续调用将一遍又一遍地拒绝相同的',',因此永远不会取得任何进展.如果检查返回值是否为零(表示早期匹配失败),则可以避免此无限循环.在再次调用scanf之前,还必须从输入流中删除无效字符.

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.

也请参见 引起无限循环的scanf() .

See scanf() causing infinite loop as well.