gpt4 book ai didi

c - scanf 格式字符串中的非空白字符

转载 作者:行者123 更新时间:2023-12-03 18:53:15 25 4
gpt4 key购买 nike

我有一个关于 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/

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