scanf() 到底如何工作?

发布于 2024-08-18 09:23:59 字数 303 浏览 2 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

摇划花蜜的午后 2024-08-25 09:24:00

无法理解问题,但 scanf 会忽略所有空白字符。 n 是一个空白字符。如果你想检测用户何时按下 Enter 键,你应该使用 fgets。

fgets(str, 10, stdin);

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.

fgets(str, 10, stdin);
乖乖兔^ω^ 2024-08-25 09:23:59

从 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. ]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文