我想写多个字符串, 每个字符串是一个单词, 单词间以空格隔开 当输入回车键时自动结束整个输入表示一个句子, 并且内存是动态分配的, 不确定有多长, 该咋写啊
用二维数组 或者指针数组加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 Excel发现不可读取的内容
- ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
- ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
- ¥20 yolov5自定义Prune报错,如何解决?
- ¥15 电磁场的matlab仿真
- ¥15 mars2d在vue3中的引入问题
- ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
- ¥15 算法题:数的划分,用记忆化DFS做WA求调
- ¥15 chatglm-6b应用到django项目中,模型加载失败
- ¥15 CreateBitmapFromWicBitmap内存释放问题。