[英]How to read a .txt file in C and store the numbers into a 2D array
So I have the following Matrix in a .txt file given to me by my professor:所以我在教授给我的 .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
and I'm suppose to be able to store the first 4 elements in each row into a 2D array.我假设能够将每行中的前 4 个元素存储到一个二维数组中。 However, I can't seem to figure out how to do it for a 2D array.
但是,我似乎无法弄清楚如何为 2D 数组执行此操作。 Any suggestions?
有什么建议?
Edit: Here is what I have so far:编辑:这是我到目前为止所拥有的:
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 is the number of elements i have to store from each row, and examples is the number of rows in the Matrix.属性是我必须从每一行存储的元素数,示例是矩阵中的行数。 Is this method even viable?
这种方法甚至可行吗?
you could try sscanf
你可以试试
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.