2017-05-11 19 views
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: 
+1

不要使用'scanf'作为字符串,使用'fgets'。 –

+0

请注意stdio缓冲整行输入。 Scanf不从键盘读取;它从该缓冲区读取。 –

回答

2

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 
相关问题