具有多个单词的字符串的 scanf() 行为

scanf() behaviour for strings with more than one word

嗯,我用 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.why 确实 scanf() 在我们按回车键后停止扫描。如果 enter 也是字符,为什么不能将其添加为正在扫描的字符串的组成部分。

2.My 第二个问题,我最需要的是,当 space 又是一个字符时,为什么它在 space 后停止扫描?

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

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

根据我对你问题的阅读,你的两个编号问题是相同的:

Why does scanf with a format specifier of %s stop reading after encountering a space or newline.

你的两个问题的答案是:因为这是 scanf%s 格式说明符的记录。

来自the documentation

%s Matches a sequence of bytes that are not white-space characters.

一个space和一个换行符(由回车键生成)是白色-space字符。

"why does scanf() stops scanning after we press enter." 并不总是正确的。

"%s"指挥scanf()如下

char buffer[100];
scanf("%s", buffer);
  1. 扫描并消耗所有白色-space,包括从多个 输入生成的'\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

  1. 扫描并保存所有非白色-space字符。继续这样做,直到遇到白色-space。

Matches a sequence of non-white-space characters §7.21.6.2 12

  1. 这个白-space放回stdin用于下一个输入函数。 (OP 的第二个问题)
  2. 空字符附加到 buffer
  3. 如果发生 EOF,操作可能会短暂停止。
  4. 如果buffer中保存的数据太多,就是UB。
  5. 如果保存了一些非白-space数据,return 1.如果遇到EOF,return EOF。

注意:stdin 通常是行缓冲的,因此在出现 '\n' 之前,不会向 stdin 提供键盘数据。

我用 scanf 制作了小程序,用于在 space 上不停地获取多个名称或输入。 我用 while

Scanf("%s",text);

While (1)
{
Scanf("%s",text1)
If (text1=='.'){break;}
//here i simple add text1 to text
}

如果使用 . 现在我用 scanf("%[^\n]",文本); 效果很好。