-1

我正在尝试使用以下代码来读取句子(字符串),然后显示句子中的单词。它没有按应有的方式显示。我究竟做错了什么?

#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;
}
4

3 回答 3

0

你的while循环逻辑是错误的;它应该是:

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

此外,您永远不会将终止的空字符 ( '\0') 写入words[],因此printf()调用将失败。

于 2012-11-09T20:52:56.740 回答
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
    }
}
于 2012-11-09T20:54:17.710 回答
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;
}
于 2012-11-09T21:11:12.010 回答