0
我是摆弄C,碰巧写下面的代码。当我输入一个带空格的字符串时,程序接收所有的输入,但是输出它们,就好像它们在不同时间以单个字输入一样。我认为scanf在遇到第一个空白字符时停止,并忽略其余部分。但似乎并非如此。有趣的行为,当在一个循环中的空间与字符串使用scanf
我在下面输入“inputWithNoSpaces”和“带空格的输入”时包含了输出。
我试图寻找stdin。它接收所有的输入。但我无法弄清楚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'作为字符串,使用'fgets'。 –
请注意stdio缓冲整行输入。 Scanf不从键盘读取;它从该缓冲区读取。 –