我在摆弄C,碰巧在下面写了代码。当我输入一个带空格的字符串时,程序接收所有输入,但输出它们就像它们在不同时间作为单个单词输入一样。我认为 scanf 在遇到第一个空白字符时停止并忽略其余部分。但事实似乎并非如此。
我在下面输入“inputWithNoSpaces”和“input with spaces”时包括了输出。
我试图查看标准输入。它接收所有输入。但是我不知道 scanf 在做什么。我想了解正在发生的事情。
代码:
#include <stdio.h>
int main()
{
int i=0;
char word[64]="";
while(1)
{
printf("enter string:");
scanf("%s",word);
i++;
printf("%d:%s\n\n",i,word);
}
return 0;
}
输出:
enter string:inputWithNoSpaces
1:inputWithNoSpaces
enter string:input with spaces
2:input
enter string:3:with
enter string:4:spaces
enter string:
最佳答案
在 scanf()
中,"%s"
表示“跳过空白字符,然后读取一系列非空白字符”。因此,当您给它输入 input with spaces
时,它将返回 "input"
、"with"
和 "spaces"
在三个顺序调用中。这是预期的行为。有关更多信息,请阅读 manual page .
input with spaces
^^^^^ First scanf("%s", s) reads this
^ Second scanf("%s", s) skips over this whitespace
^^^^ Second scanf("%s", s) reads this
^ Third scanf("%s", s) skips over this whitespace
^^^^^^ Third scanf("%s", s) reads this
关于c - 在循环中对带空格的字符串使用 scanf 时的有趣行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43912347/