gpt4 book ai didi

c - scanf() 对包含多个单词的字符串的行为

转载 作者:行者123 更新时间:2023-11-30 21:15:21 24 4
gpt4 key购买 nike

我已经用C编程有一段时间了,有一个关于函数scanf()的问题

这是我的问题:

I know that every element in ASCII table is a character and I even know that %s is a data specified for a string which is a collection of characters

我的问题:

1.为什么按回车后scanf()停止扫描。如果 Enter 也是字符,为什么不能将其添加为正在扫描的字符串的组成部分。

2.我的第二个问题也是我最需要的是,当空格再次成为一个字符时,为什么它会在空格之后停止扫描?

Note: My question is not about how to avoid these but how does this happen

如果这个问题已经得到解决,我会很高兴,我很乐意删除我的问题,即使我认为有问题,也请告诉我

最佳答案

“为什么 scanf() 在我们按下 Enter 后停止扫描。”并不总是正确的。

"%s"指挥scanf()如下

char buffer[100];
scanf("%s", buffer);
  1. 扫描并消耗所有空白,包括 '\n'多个 输入生成。此数据不会保存。

Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier C11dr §7.21.6.2 8

  • 扫描并保存所有非空白字符。继续这样做,直到遇到空格。
  • Matches a sequence of non-white-space characters §7.21.6.2 12

  • 这个空白被放回 stdin用于下一个输入功能。 (OP的第二个问题)
  • 将空字符附加到buffer .
  • 如果发生 EOF,操作可能会短暂停止。
  • 如果 buffer 中保存的数据过多,是UB。
  • 如果保存了一些非空白数据,则返回1。如果遇到EOF,则返回EOF。
  • 注:stdin通常是行缓冲的,因此没有键盘数据提供给 stdin直到'\n'发生。

    关于c - scanf() 对包含多个单词的字符串的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34007197/

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