我想写多个字符串, 每个字符串是一个单词, 单词间以空格隔开 当输入回车键时自动结束整个输入表示一个句子, 并且内存是动态分配的, 不确定有多长, 该咋写啊
用二维数组 或者指针数组加malloc 简洁明了的
分两种情况,如果你能够确定句子的最大长度,可以用下面的写法:
int main()
{
char str[1024] = {0};
char* pstr = str;
char* pos = str;
char** result;
fgets(str , 1024 , stdin);
int space_count = 0;
while (*pstr != '\0')
{
if (*pstr++ == ' ')
space_count ++;
}
pstr = str;
result = (char**)calloc(sizeof(char*) , space_count + 1);
for (int i = 0 ; i <= space_count ; i ++)
{
while (*pstr != ' ' && *pstr != '\0')
pstr ++;
*pstr++ = '\0';
printf("%d:%s\n" , i , pos);
result[i] = malloc(sizeof(strlen(pos)));
strcpy(result[i] , pos);
pos = pstr;
}
for(int i = 0 ; i <= space_count ; i ++)
printf("%s\n" , result[i]);
return 0;
}
如果你完全什么都不确定,只能用更复杂的写法:
int main()
{
#ifndef WORDLIMIT
#define WORDLIMIT 10
#endif
char* tmpword = calloc(sizeof(char) , WORDLIMIT);
char** result = NULL;
char ch;
int curlimit = WORDLIMIT;
int wordlen = 0;
int mul = 1;
int wordcount = 0;
while ((ch = getche()) != '\n' && ch != '\r')
{
if (ch != ' ')
{
if (wordlen == curlimit)
{
tmpword = realloc(tmpword , (curlimit + WORDLIMIT) * sizeof(char));
if (!tmpword)
exit(-1);
}
tmpword[wordlen ++] = ch;
}
else
{
tmpword[wordlen] = '\0';
wordcount ++;
result = realloc(result , wordcount * sizeof(char*));
if (!result)
exit(-1);
result[wordcount - 1] = malloc(sizeof(char) * strlen(tmpword));
strcpy(result[wordcount - 1] , tmpword);
wordlen = 0;
mul = 1;
curlimit = WORDLIMIT;
}
}
//处理最后一个单词
if (wordlen == curlimit)
{
tmpword = realloc(tmpword , (curlimit + WORDLIMIT) * sizeof(char));
if (!tmpword)
exit(-1);
}
tmpword[wordlen] = '\0';
wordcount ++;
result = realloc(result , wordcount * sizeof(char*));
if (!result)
exit(-1);
result[wordcount - 1] = malloc(sizeof(char) * strlen(tmpword));
strcpy(result[wordcount - 1] , tmpword);
for (int i = 0 ; i < wordcount ; i ++)
printf("\n%s" , result[i]);
return 0;
}
第二种方法很不好用,也可能是我没写好没有优化的原因,但是就这样的写法而言,一旦输错了一个字,输入退格是没有用的。
上面第二份代码中有个地方写错了,
if (ch != ' ')
{
if (wordlen == curlimit)
{
tmpword = realloc(tmpword , (curlimit + WORDLIMIT) * sizeof(char));
if (!tmpword)
exit(-1);
curlimit += WORDLIMIT;//这里漏了,不加会造成数据丢失
}
tmpword[wordlen ++] = ch;
}