假设我想运行以下 C 代码片段:
scanf("%d" , &some_variable);
printf("something something\n\n");
printf("Press [enter] to continue...")
getchar(); //placed to give the user some time to read the something something
Run Code Online (Sandbox Code Playgroud)
这个片段不会暂停!问题是 会将scanf
“enter”( \n
)字符留在输入流1中,弄乱其后面的所有内容;在这种情况下,他们getchar()
会吃掉\n
而不是等待真正的新角色。
由于我被告知不要使用fflush(stdin)
(我真的不明白为什么),我能想出的最佳解决方案就是在代码开头重新定义扫描函数:
void nsis(int *pointer){ //nsis arconim of: no shenanigans integer scanf
scanf("%d" , pointer);
getchar(); //this will clean the inputstream every time the scan function is called
}
Run Code Online (Sandbox Code Playgroud)
然后我们只需使用nsis
代替scanf
. 这应该会飞。然而,这似乎是一个真正自制的、用胶带组合在一起的解决方案。专业的 C 开发人员如何处理这个烂摊子?scanf
他们根本不使用吗?他们是否只是接受使用脏输入流?这里的标准是什么?
我无法在任何地方找到明确的答案!我能找到的每个来源都提到了不同的(且粗略的)解决方案......
编辑:回应所有评论某些版本的“只是不要使用 …