如何在C中读取.txt文件并将数字存储到2D数组中

时间:2017-10-19 03:42:49

标签: c

所以我在教授给我的.txt文件中有以下Matrix:

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);

attributes是我必须从每行存储的元素数,而examples是Matrix中的行数。这种方法是否可行?

1 个答案:

答案 0 :(得分:0)

您可以尝试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);