按回车键时 scanf 不 return

scanf doesn't return when pressing enter

过去一个小时我都在试图找出原因

char buffer[101];
scanf("%100[^\n]", buffer);

按预期工作,读取字符串直到遇到换行符,而

char buffer[101];
scanf("%100[^\n]\n", buffer);

在按 Enter 后不会 return。

使用 CtrlD 显式刷新输入缓冲区(在 linux 中) 按 Enter 后立即似乎解决了问题, 强制 scanf 为 return。我在这里遗漏了什么吗?

是的,您错过了一个有据可查的重要细节。根据the scanf manual...

A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.

这意味着 scanf 确实不会 return 当您按回车键时;它会继续等待,看看你是否再次按回车键(或 space,或 tab)……一次又一次……直到它看到不是白色的东西-space.

如果你想丢弃 scanset 指令后留下的 '\n',你可以像这样使用 %*cint x = scanf("%100[^\n]%*c", buffer);...

P.S。不要忘记检查 x 的值。当您使用 scanset 指令时,这一点尤为重要,因为在这种情况下,空行将导致未初始化的 buffer