Re: [問題] 字串分開實作
感謝各位的回答。
我後來還是用了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
06/13 07:55, 1F
→
06/13 07:56, , 2F
06/13 07:56, 2F
推
06/13 08:02, , 3F
06/13 08:02, 3F
→
06/13 20:34, , 4F
06/13 20:34, 4F
→
06/13 20:35, , 5F
06/13 20:35, 5F
推
06/14 00:32, , 6F
06/14 00:32, 6F
→
06/14 00:33, , 7F
06/14 00:33, 7F
→
06/15 14:08, , 8F
06/15 14:08, 8F
→
06/15 14:36, , 9F
06/15 14:36, 9F
→
06/15 14:41, , 10F
06/15 14:41, 10F
→
06/19 17:45, , 11F
06/19 17:45, 11F
討論串 (同標題文章)