Clearing the buffer when using Getchar (there must be a better way!)

我与影子孤独终老i 提交于 2019-12-01 12:15:51

Note that fflush(stdin) is undefined behavior according to the C Standard, though it is supported by a few implementations.

The idiomatic way to do this is:

int c;
while ((c = getchar()) != '\n' && c != EOF) {
    continue;
}

The check for EOF is needed to avoid an infinite loop in the event that there is an error in getchar(), or if the user signals EOF from the keyboard. The variable c needs to be an int to ensure that it can hold the value of EOF, which is typically -1.

Also be aware that this method requires that there be at least one character left in the input stream, otherwise getchar() will block, waiting for input. A previous call to getchar() or scanf() will leave at least a newline behind, but calls to fgets() may not.

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