2011-09-10 38 views
0

我知道scanf是如何被用於分析句子爲單個單詞:你可以用`scanf`解析句子並檢測換行符嗎?

while(1){ 
    scanf("%s", buffer) 
    ... 
} 

但是,如果我進入一句話one two three<return>,我怎麼能找到一個while循環中,如果這個詞我越來越在緩衝區中是我按下<return>之前的那個?

我想scanf幾乎不可能,但也許有類似的功能?

回答

2

您應該使用fgets()讀取整個行,並解析它,像這樣:

char buffer[BUFSIZE] = {};  // BUFSIZE should be large enough for one line 
fgets(buffer, BUFSIZE, stdin); // read from standard input, same as scanf 
char *ptr = strtok(buffer, " "); // second argument is a string of delimiters 
            // can be " ,." etc. 
while (ptr != NULL) { 
    printf("Word: '%s'\n", ptr); 

    ptr = strtok(NULL, " ");  // note the NULL 
} 

檢查,如果當前的字是硬道理,是微不足道的:

while (ptr != NULL) { 
    char word[BUFSIZE] = {}; 
    strcpy(word, ptr);   // strtok clobbers the string it is parsing 
           // So we copy current string somewhere else. 
    ptr = strtok(NULL, " "); 

    bool is_last_word = (ptr == NULL); 
    // do your thing here with word[] 
} 
+0

你只是在知道線條長度不會超過(BUFSIZE-1)個字符。如果它更多,你最終會在fgets()調用中破壞單詞。 –

+0

正確,因此我在旁邊發表評論。唯一的另一種方法是使用動態分配的字符串緩衝區,這不在此問題的範圍之內。而且,如果你這樣做,你最好使用C++和它的字符串流。 – evgeny

0

如果你只對最後一個詞感興趣,你可以合理輕鬆地做到這一點。如果行數超過緩衝區大小,則提供的fgets()解決方案容易出現併發症 - 您可能會在多個fgets()調用中分割一個詞。你應該準備好應對這種可能性。 ()它本身是危險的 - 它會將任意長度的單詞讀入緩衝區。如果您依賴它,請始終記住使用%s和長度說明符。我很確定你實際上不能使用scanf()來實現你所需要的。

您最好按字符處理輸入字符。當你打開一個空間時,你正在休息一下。當你擊中換行符時,你就是最後一個詞。

相關問題