在C中使用字符串数组

在C中使用字符串数组,c,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(

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

#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;
}
#包括
#包括
#定义N 100
int main()
{
chars[N];
字符字[N][N];
int i=0;
int j=0;
printf(“s=”);
获取(s);

while((i您的while循环逻辑是错误的;它应该是:

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

另外,您从不将终止空字符(
'\0'
)写入
单词[]
,因此
printf()
调用将失败。

未测试,但您应该了解:

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
    }
}
int size=strlen;
int start=0;
对于(i=0;i
#包括
#包括
#定义N 100
int main()
{
chars[N];
char words[N][N]={0};/*此初始值将您的数组设置为0*/
int i=0;
int j=0;
printf(“s=”);
获取(s);

而((通常我们在这些情况下使用调试器…)不要让我们猜错了什么。请描述输入、预期输出和实际输出。
sprintf(words[j],“%c”,s[i])
的意思是既不大于也不小于
words[j][0]=s[i];words[j][1]=0
。除了每个单词的第一个位置,您永远不会在其他位置赋值。不需要终止空字符(
'\0'
),因为他使用
sprintf()
sprintf()
函数终止字符串缓冲区(
'\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;
}