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

标签 c scanf

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/

相关文章:

c - 0.00001 增量

c - Scanf和指针的误解

c - 打印列数和行数为奇数的数组的值

c - 打印从用户获得的 int 值

c - 如何在C中使用printf和scanf读写文件?

比较 void * 是否包含 0 个字节?

c - 矩阵乘法:为什么非阻塞优于阻塞?

c - 需要有关 CS50 使用 'C' 的 luhns 算法的帮助

c - 读入一个数组

c - scanf() 将换行符保留在缓冲区中