所以我的教授给我的.txt文件中有以下矩阵:
3.000000,1.000000,1180.000000,1955.000000,221900.000000
3.000000,2.250000,2570.000000,1951.000000,538000.000000
2.000000,1.000000,770.000000,1933.000000,180000.000000
4.000000,3.000000,1960.000000,1965.000000,604000.000000
3.000000,2.000000,1680.000000,1987.000000,510000.000000
4.000000,4.500000,5420.000000,2001.000000,1230000.000000
3.000000,2.250000,1715.000000,1995.000000,257500.000000
3.000000,1.500000,1060.000000,1963.000000,291850.000000
3.000000,1.000000,1780.000000,1960.000000,229500.000000
3.000000,2.500000,1890.000000,2003.000000,323000.000000
并且我想能够将每行中的前4个元素存储到2D数组中。但是,我似乎无法弄清楚如何对2D数组进行处理。有什么建议么?
编辑:
这是我到目前为止的内容:
int main(int argc, char *argv[]){
FILE *train;
FILE *test;
int row,cols;
int num = 0;
char single [150];
char single1 [150];
train = fopen(argv[1],"r");
test = fopen(argv[2],"r");
if(argc < 3){
printf("error\n");
return 0;
}
char *a = fgets(single,150,train);
int attributes = atoi(a);
char *b = fgets(single,150,train);
int examples = atoi(b);
printf("%d\n%d\n\n",attributes,examples);
int matX[attributes][examples];
for(row = 0; row < attributes;row++){
for(cols = 0; cols < examples;cols++){
matX[row][cols] = atoi(fgets(single,150,train));
}
}
printArray(row,cols,matX);
属性是我必须从每一行存储的元素数,而示例是矩阵中的行数。这种方法是否可行?
最佳答案
您可以尝试sscanf
char line ="3.000000,1.000000,1180.000000,1955.000000,221900.000000";
float v0, v1, v2, v3;
sscanf(line, "%f,%f,%f,%f", &v0, &v1, &v2, &v3);
关于c - 如何在C中读取.text文件并将数字存储到2D数组中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46822486/