2011-11-15 69 views

回答

3

如果要重複使用buffer,則需要兩次調用scanf,每個字符串一個。

ret = scanf("%s", buffer); 
/* Check that ret == 1 (one item read) and use contents of buffer */ 

ret = scanf("%s", buffer); 
/* Check that ret == 1 (one item read) and use contents of buffer */ 

如果你想使用兩個緩衝區,那麼你可以將這個變成一個調用scanf

ret = scanf("%s%s", buffer1, buffer2); 
/* Check that ret == 2 (two items read) and use contents of the buffers */ 

注意,這類閱讀串本質上是不安全的,因爲其中沒有防止長串從控制檯輸入溢出緩衝區。見http://en.wikipedia.org/wiki/Scanf#Security

要解決此問題,應指定要讀取的字符串的最大長度(減去終止空字符)。使用的128個字符緩衝區的例子:

ret = scanf("%127s%127s", buffer1, buffer2); 
/* Check that ret == 2 (two items read) and use contents of the buffers */ 
+0

這是爲什麼需要?你能不能讓scanf接受兩個字符串? –

+1

如果您想將兩個字符串存儲在一個緩衝區中,一個接一個地處理它們,這個答案是完全正確的。用兩個字符串你有兩個指針,兩個緩衝區,兩個內存分配來清理。我給+1。 –

+0

我相信這兩種選擇都有效,不是嗎? –

5
char buffer[128], buffer2[128]; 
ret = scanf("%s %s", buffer, buffer2); 
1

您需要選擇第一和第二串兩個不同的位置。

char buffer1[100], buffer2[100]; 
if (scanf("%99s%99s", buffer1, buffer2) != 2) /* deal with error */; 
0

如果你知道你想讀的單詞數,你可以把它讀作:

char buffer1[128], buffer2[128]; 
ret = scanf("%s %s", buffer1, buffer2); 

或者您可以使用fgets()函數獲取多字字符串。

fgets(buffer, 128 , stdin); 

See Example

0

#include<stdio.h>

int main(){ 
int i = 0,j =0; 
char last_name[10]={0}; 
printf("Enter sentence:"); 
i=scanf("%*s %s", last_name); 
j=printf("String: %s",last_name)-8; 
/* Printf returns number of characters printed.(String:)is adiitionally 
printed having total 8 characters.So 8 is subtracted here.*/ 
printf("\nString Accepted: %d\nNumber of character in string: %d",i,j); 
return 0; 
} 
相關問題