2017-05-11 20 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 
相關問題