在循环中带有空格的字符串上使用scanf时的有趣行为

在循环中带有空格的字符串上使用scanf时的有趣行为,c,string,scanf,C,String,Scanf,我在摆弄C,碰巧写了下面的代码。当我输入一个带空格的字符串时,程序接收所有输入,但输出它们,就好像它们在不同的时间作为单个单词输入一样。我认为scanf在遇到第一个空白字符时停止了,而忽略了其余的字符。但情况似乎并非如此 我在下面输入“inputWithNoSpaces”和“inputwithspaces”时包含了输出 我试着调查斯丁。它接收所有的输入。但我不知道scanf在做什么。我想知道发生了什么 代码: 在scanf()中,“%s”表示“跳过空白字符,然后读取一系列非空白字符”。因此,当您

我在摆弄C,碰巧写了下面的代码。当我输入一个带空格的字符串时,程序接收所有输入,但输出它们,就好像它们在不同的时间作为单个单词输入一样。我认为scanf在遇到第一个空白字符时停止了,而忽略了其余的字符。但情况似乎并非如此

我在下面输入“inputWithNoSpaces”和“inputwithspaces”时包含了输出

我试着调查斯丁。它接收所有的输入。但我不知道scanf在做什么。我想知道发生了什么

代码:

scanf()
中,
“%s”
表示“跳过空白字符,然后读取一系列非空白字符”。因此,当您给它输入带有空格的
时,它将在三个连续调用中返回
“input”
“input”
“spaces”
。这是预期的行为。有关更多信息,请阅读

scanf()
中,
“%s”
表示“跳过空白字符,然后读取一系列非空白字符”。因此,当您给它输入带有空格的
时,它将在三个连续调用中返回
“input”
“input”
“spaces”
。这是预期的行为。有关更多信息,请阅读


不要对字符串使用
scanf
,请使用
fgets
。请注意stdio会缓冲整行输入。Scanf不从键盘读取数据;它从该缓冲区读取。不要对字符串使用
scanf
,请使用
fgets
。请注意stdio会缓冲整行输入。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:
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