Re: [问题] 字串分开实作

楼主: wtchen (没有存在感的人)   2015-06-13 02:17:04
感谢各位的回答。
我后来还是用了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);
}
作者: arthur104 (arthur)   2015-06-13 07:55:00
line:34,76有问题吧! 然后strcpy -> 安全些, 然后档案有机会开了没关,最后是malloc你不能保证一定成功。
楼主: wtchen (没有存在感的人)   2015-06-13 20:34:00
line 34我试过没加不会work....有些malloc不需要是真的(说真的也只是想多练习pointer)
作者: arthur104 (arthur)   2015-06-14 00:32:00
title[i]的size会是错的吧没加当然不会动@@
作者: anyoiuo   2015-06-15 14:08:00
70, 76行删了吧!title[i]有malloc但没有free, 所以Memory leak!然后就arthur大大提到的size, 不要用sizeof用strlen + 1
楼主: wtchen (没有存在感的人)   2015-06-19 17:45:00
感谢,已修正,真的得多练习coding...

Links booklink

Contact Us: admin [ a t ] ucptt.com