我的方法读取具有以下格式的向量输入文本:
57.0000,-7.4703,-0.3561
81.0000,-4.6478,7.9474
69.0000,-8.3768,0.4391
18.0000,-4.9377,9.9903
62.0000,-5.8751,-6.6054
...
我尝试读取每个向量并将其插入到数组中如下:
FILE *file;
int n = 1, dim, i=0;
char* str;
double ret;
double* X;
int c;
int com=0;
assert(argc==2 && "argc != 2");
file = fopen(argv[1], "r");
assert(file && "file is empty");
for(c = getc(file); c!= EOF; c = getc(file)){
if(c == '\n'){
n++;
}
else if(c==','){
com++;
}
}
dim = com/n +1;
char* str;
double ret;
double* X;
X = (double *)calloc(n*n, sizeof(double));
assert(X);
str = (char *)calloc(100, sizeof(char));
assert(str);
for(c = getc(file); c!= EOF; c = getc(file)){
if(c!=',' && c!= '\n'){
strcat(str, &c);
}
else{
ret = strtod(str, NULL);
X[i] = ret;
i++;
memset(str, 0, 100 * sizeof(char));
}
}
问题是当它到达每一行的最后一个向量时,它会读取每个字符并将其与额外的垃圾连接到 str 中。任何想法如何解决这个问题?