我有一个关于 scanf 函数在遇到格式字符串中的非空白字符时所采取的过程的问题。根据我正在阅读的书:
When a
scanf
function encounters a non-whitespace character in a format string,scanf
compares it with the next input character. If the two characters match,scanf
discards the input character and continues processing the format string. If the characters don't match,scanf
puts the offending character back into the input, then aborts without further processing the format string or reading characters from the input.
我有点困惑。它说
scanf
将其与下一个输入字符进行比较,如果两个字符匹配,则 scanf
丢弃输入字符。为什么我们说它与“下一个”输入字符进行比较?这是否意味着如果我们有一个格式字符串
scanf("%d/%d", &x, &y)
和输入 2/4
, scanf
与四个比较,因为它是来自 /
的下一个输入字符?
最佳答案
另一种描述方式 scanf
是对于非空白字符,它跟随输入以及它期望在格式字符串中看到的内容。但是,如果它找到不同的读取器,它会“未读取”该字符,然后完全停止扫描。
例如,让我们看看:
int x, y;
int scanned = scanf("%dabc%d", &x, &y);
如果我们给它输入 10abc20
,然后按以下顺序运行:%d
, 阅读 10
,并将其存储在 x
. abc
并跟随 abc
在格式字符串中给出。 %d
, 阅读 20
,并将其存储在 y
. 2
用于扫描两个值。 给同一个程序
10abz20
反而:%d
, 阅读 10
,并将其存储在 x
. ab
正确但当它到达 z
,未读取该字符,并提前返回值 1
,因为它只扫描了第一个数字。 z20
未读,可以在程序稍后阅读。 所以在你的例子中
scanf("%d/%d", &x, &y)
, 输入 10/20
将完全扫描,但 10d20
只会扫描 10
进入x然后离开d20
未读。顺便说一句,10/ 20
和 10/20
完全扫描,但 10 /20
才不是。
关于c - scanf 格式字符串中的非空白字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66514456/