gpt4 book ai didi

c - 为什么 scanf 不遵循带有非空白字符的文档?

转载 作者:太空宇宙 更新时间:2023-11-04 05:24:26 26 4
gpt4 key购买 nike

documentation on scanf表示格式中的任何“非空白字符”,都会导致函数从流中读取下一个字符,将其与该非空白字符进行比较,如果匹配,则将其丢弃,函数继续处理下一个字符格式。 如果字符不匹配,则函数失败,返回并留下未读流的后续字符。

但是,如果我运行:

int x;
while(scanf("\n%d",&x)==1) printf("%d\n",x);

使用以下输入:

1 2

它打印:

1
2

鉴于两个数字中的任何一个之前都没有“\n”,为什么 scanf 会读取它们?这不是违反文档吗?

最佳答案

在您链接到的同一页面和您引用的段落之前,我看到:

  • Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

\n 是一个空白字符。

因此,调用

scanf("\n%d",&x)

在将数据读入&x 之前,将从stdio 中提取并丢弃任意数量的空白字符。

关于c - 为什么 scanf 不遵循带有非空白字符的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37931258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com