Why aren't scanf(“%*[^\\n]\\n”); and scanf(“%*[^\\n]%*c”); clearing a hanging newline?

房东的猫 提交于 2019-12-05 16:19:49

The basic problem is that the scanf pattern %[^\n] matches ONE OR MORE characters that are not newlines. So if the next character is a newline, the pattern will fail and scanf will return immediately without reading anything. Add a * doesn't change that basic fact. So it turns out you can't do this with only one call, you need two:

scanf("%*[^\n]"); scanf("%*c");

Note that putting a bare newline into the scan pattern is almost always not useful -- it causes scanf to read and discard all whitespace until it sees a non-whitespace character (which will be left in the input buffer). Particularly if you try to use it in an interactive program, it will appear to hang until you enter a non-blank line.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!