且构网

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

如何防止scanf失败的无限循环

更新时间:2023-11-14 22:11:40

如果提供了除scanf()格式说明符的预期值以外的不适当值,则scanf()将失败并且不当值保留在输入缓冲区中,将 feed 提供给下一个scanf(),只会导致连续失败.在这种情况下,您需要清理输入缓冲区,然后再进行下一个输入.您可以使用类似的

In case an inappropriate value is supplied other than the expected value of the format specifier with scanf(), the scanf() will fail and the inappropriate value will remain in the input buffer, providing the feed to next scanf(), only to cause successive failures. In that case, you need to clean up the input buffer before going for next input. You can use something like

  1. 检查scanf()
  2. 的返回值
  3. 万一发生故障,请使用while( getchar() != '\n' );清理输入缓冲区.
  1. check the return value of scanf()
  2. In case of failure, use while( getchar() != '\n' ); to clean the input buffer.

也就是说,int nickels(numChange)现在在c中(C99起)无效.您必须明确地将其设置为int.

That said, int nickels(numChange) is now invalid in c (C99 onwards). You have to make it as int explicitly.