Re: [問題] 字串分開實作

看板C_and_CPP作者 (沒有存在感的人)時間9年前 (2015/06/13 02:17), 編輯推噓3(308)
留言11則, 3人參與, 最新討論串2/2 (看更多)
感謝各位的回答。 我後來還是用了strtok來做。 大概把我想要的樣子都弄出來了。 感想:1. 程式語言很多東西不自己實際演練過還真的不會了解。 2. pointer真的是很好玩的東西,有它在我就不會想去玩Java了。 程式碼更新在此: https://gist.github.com/gnitnaw/11ad7e7a98e4ebc8601f #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 256 #define NITEM 15 int getData(char* line, char** t); void outputResult(FILE *fout, char** title, char** t, int N); int main(void) { char s; int i, j, N; char **t = (char**)malloc(sizeof(char*)*NITEM); char **title = (char**)malloc(sizeof(char*)*NITEM); char* line = (char*)malloc(sizeof(char)*SIZE); FILE *fp = fopen("Example_table.txt", "r"); FILE *fout = fopen("output.txt", "a"); if (!fp) { perror("Error! Cannot find the file"); exit(1); } if (!fout) { perror("Error! Cannot create the file"); exit(2); } fgets(line,SIZE,fp); N = getData(line,t); for (i=0; i<N; ++i) { title[i] = malloc(sizeof(t[i])); strcpy(title[i], t[i]); } while(!feof(fp)) { fgets(line,SIZE,fp); j = getData(line, t); if (j<=1) continue; outputResult(stdout,title,t,j); outputResult(fout,title,t,j); } free(line); free(title); fclose(fp); fclose(fout); free(t); return 0; } int getData(char* line, char** t) { int item=0; char *c = strtok(line,"\n"); c = strtok(line,"\t"); t[item++] = c; while (c != NULL && item < NITEM) { c = strtok(NULL,"\t"); if (c!= NULL) t[item++] = c; } return item; } void outputResult(FILE *fout, char** title, char** t, int N) { int i, a; char *b; for (i=0; i<N;++i) { fprintf(fout, "%s : %s ", title[i], t[i]); if (i!=N-1) fprintf(fout, ", "); } fputc('\n',fout); free(b); } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 90.41.134.196 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1434133027.A.1D1.html

06/13 07:55, , 1F
line:34,76有問題吧! 然後strcpy -> 安全些, 然後
06/13 07:55, 1F

06/13 07:56, , 2F
檔案有機會開了沒關,最後是malloc你不能保證一定成功。
06/13 07:56, 2F

06/13 08:02, , 3F
都用define了,有些malloc其實不需要
06/13 08:02, 3F

06/13 20:34, , 4F
line 34我試過沒加不會work....
06/13 20:34, 4F

06/13 20:35, , 5F
有些malloc不需要是真的(說真的也只是想多練習pointer)
06/13 20:35, 5F

06/14 00:32, , 6F
title[i]的size會是錯的吧
06/14 00:32, 6F

06/14 00:33, , 7F
沒加當然不會動@@
06/14 00:33, 7F

06/15 14:08, , 8F
70, 76行刪了吧!
06/15 14:08, 8F

06/15 14:36, , 9F
title[i]有malloc但沒有free, 所以Memory leak!
06/15 14:36, 9F

06/15 14:41, , 10F
然後就arthur大大提到的size, 不要用sizeof用strlen + 1
06/15 14:41, 10F

06/19 17:45, , 11F
感謝,已修正,真的得多練習coding...
06/19 17:45, 11F
文章代碼(AID): #1LUo8Z7H (C_and_CPP)
文章代碼(AID): #1LUo8Z7H (C_and_CPP)