我想写多个字符串, 每个字符串是一个单词, 单词间以空格隔开 当输入回车键时自动结束整个输入表示一个句子, 并且内存是动态分配的, 不确定有多长, 该咋写啊
用二维数组 或者指针数组加malloc 简洁明了的
求大神,关于C语言的问题
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- SliveryLight 2017-04-11 17:05关注
分两种情况,如果你能够确定句子的最大长度,可以用下面的写法:
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; }
第二种方法很不好用,也可能是我没写好没有优化的原因,但是就这样的写法而言,一旦输错了一个字,输入退格是没有用的。本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 c程序不知道为什么得不到结果
- ¥40 复杂的限制性的商函数处理
- ¥15 程序不包含适用于入口点的静态Main方法
- ¥15 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
- ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
- ¥20 有关区间dp的问题求解
- ¥15 多电路系统共用电源的串扰问题
- ¥15 slam rangenet++配置