2012-11-09 69 views
-1

我想用下面的代碼來讀取一個句子(字符串),然後顯示句子的單詞。它不顯示,因爲它應該。我究竟做錯了什麼?在C中使用字符串數組

#include <stdio.h> 
#include <string.h> 
#define N 100 

int main() 
{ 
    char s[N]; 
    char words[N][N]; 
    int i=0; 
    int j=0; 
    printf("s="); 
    gets(s); 
    while ((i<strlen(s)) && (s[i]!='.')) 
    { 
     while (s[i]!= ' ') 
     { 
      sprintf(words[j],"%c", s[i]); 
      i++; 
     } 
     j++; i++; 
    } 
    for (i=0;i<j;i++) printf("%s ", words[i]); 
    return 0; 
} 
+2

通常我們在這些情況下使用調試器...... – pmod

+1

不要讓我們猜測什麼是錯的。描述輸入,預期輸出和實際輸出。 –

+1

'sprintf(words [j],「%c」,s [i])'既不多也不少於'words [j] [0] = s [i];字[j]的[1] = 0'。除了每個單詞的第一個位置,你永遠不會分配任何其他地方。 –

回答

0

您的while循環邏輯錯誤;它應該是:

int k = 0; 
while (s[i] != ' ') 
    words[j][k++] = s[i++]; 
words[j][k] = '\0'; 

而且,你永遠不會寫一個終止空字符('\0')到words[],所以printf()調用將失敗。

+0

因爲他使用'sprintf()'而'sprintf()'函數用(''\ 0'')終止字符串緩衝區,所以不需要終止空字符(''\ 0'') – MOHAMED

0

未經測試,但你應該得到的想法:

int size = strlen(s); 
int start = 0; 
for(i = 0; i < size; i++) { 
    if (s[i] == ' ') { 
     char* word = malloc((i-start)*size(char)+1); // alloc memory for a word 
     strcpy(word, s+size(char)*i, i-start); // copy only the selected word 
     word[i-start+1] = '\0'; // add '\0' at the end of string 
     printf("%s\n", word); 
     start = i + 1; // set new start index value 
    } 
} 
0
#include <stdio.h> 
#include <string.h> 
#define N 100 

int main() 
{ 
    char s[N]; 
    char words[N][N] = {0} ; /* this initial your array to 0 */ 
    int i=0; 
    int j=0; 
    printf("s="); 
    gets(s); 
    while ((i<strlen(s)) && (s[i]!='.')) 
    { 
     while (s[i]!= ' ') 
     { 
      sprintf(words[j]+strlen(words[j]),"%c", s[i]); /* this will concat chars in words[j] */ 
      i++; 
     } 
     j++; i++; 
    } 
    for (i=0;i<j;i++) printf("%s ", words[i]); 
    return 0; 
}