【发布时间】:2021-11-05 10:19:13
【问题描述】:
我的方法读取具有以下格式的向量输入文本:
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 中。任何想法如何解决这个问题?
【问题讨论】:
-
c的类型没有显示(编辑前),但是肯定不适合传给strcat,因为你有c = getc(file)所以应该是int类型。 -
卡哈隆,第一步:
char c;-->int c; -
strcat(str, &c);无效,因为&c不指向字符串。 -
请记住,
'-'是类型int而不是char。不使用int就无法测试EOF,这是库函数getc返回的结果,不是char。 -
然后阅读@chux 的评论。你不能
strcat一个字符,你需要一个字符串。
标签: c file strcat garbage getc