2012-11-09 71 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; 
}