scanf() 到底如何工作?
在 Windows 上,
char c;
int i;
scanf("%d", &i);
scanf("%c", &c);
计算机会跳过从控制台检索字符,因为“\n”仍保留在缓冲区中。 但是,我发现下面的代码运行良好。
char str[10];
int i;
scanf("%d", &i);
scanf("%s", str);
就像上面的情况一样,'\n' 保留在缓冲区中,但为什么 scanf 这次成功从控制台获取字符串?
On Windows,
char c;
int i;
scanf("%d", &i);
scanf("%c", &c);
The computer skips to retrieve character from console because '\n' is remaining on buffer.
However, I found out that the code below works well.
char str[10];
int i;
scanf("%d", &i);
scanf("%s", str);
Just like the case above, '\n' is remaining on buffer but why scanf successfully gets the string from console this time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无法理解问题,但 scanf 会忽略所有空白字符。
n
是一个空白字符。如果你想检测用户何时按下 Enter 键,你应该使用 fgets。Having trouble understanding the question, but scanf ignores all whitespace characters.
n
is a whitespace character. If you want to detect when user presses enter you should use fgets.从 gcc 手册页(我没有方便的 Windows):
%c:始终匹配固定数量的字符。最大字段宽度说明如何
许多字符需要阅读;如果不指定最大值,则默认值为 1。它也不会跳过初始空白字符。
%s:匹配非空白字符的字符串。 它会跳过并丢弃初始的
空格,但在读取内容后遇到更多空格时停止。
[ 此条款应解释您所看到的行为。 ]
From the gcc man page (I don't have Windows handy):
%c: matches a fixed number of characters, always. The maximum field width says how
many characters to read; if you don't specify the maximum, the default is 1. It also does not skip over initial whitespace characters.
%s: matches a string of non-whitespace characters. It skips and discards initial
whitespace, but stops when it encounters more whitespace after having read something.
[ This clause should explain the behaviour you are seeing. ]