[英]how to read from text file and store in matrix in c
首先要说的是,我是编码的新手,所以请宽恕我的错误。 我现在正试图从一个相当大的txt文件中读取文件,它大约有1000000行和4列
56.154 59.365 98.3333 20.11125
98.54 69.3645 52.3333 69.876
76.154 29.365 34.3333 75.114
37.154 57.365 7.0 24.768
........
........
我想全部读取它们并将它们存储到一个矩阵中,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int main()
{
int i;
int j;
/*matrix*/
int** mat=malloc(1000000*sizeof(int));
for(i=0;i<1000000;++i)
mat[i]=malloc(4*sizeof(int));
FILE *file;
file=fopen("12345.txt", "r");
for(i = 0; i < 1000; i++)
{
for(j = 0; j < 4; j++)
{
if (!fscanf(file, " %c", &mat[i][j]))
break;
mat[i][j] -= '0'; /* I found it from internet but it doesn't work*/
printf("\n",mat[i][j]);
}
}
fclose(file);
}
结果是我的矩阵中什么也没有。 我希望你能提供帮助。 在此先感谢您的帮助。
许多问题,请考虑关注,当然请参见评论
int main()
{
int i;
int j;
/*matrix*/
/*Use double , you have floating numbers not int*/
double** mat=malloc(1000000*sizeof(double*));
for(i=0;i<1000000;++i)
mat[i]=malloc(4*sizeof(double));
FILE *file;
file=fopen("1234.txt", "r");
for(i = 0; i < 1000; i++)
{
for(j = 0; j < 4; j++)
{
//Use lf format specifier, %c is for character
if (!fscanf(file, "%lf", &mat[i][j]))
break;
// mat[i][j] -= '0';
printf("%lf\n",mat[i][j]); //Use lf format specifier, \n is for new line
}
}
fclose(file);
}
您的代码在这里有几处错误。
首先,您创建一个int
矩阵,但您正在读取看起来像float值的值。 您可能想使用double
其次,当您阅读双曲时,应使用
fscanf(file, "%lf", &some_double); // fscanf(file, "%d", &some_int); for integers
同样,在分配矩阵时,您应该传递的第一个malloc
sizeof(double *) // or int * if you are really trying to use integers
最后,您的代码行:
mat[i][j] -= '0'
您想在这里完成什么? 您正在(尝试)读入一个int并减去“ 0” ...
编辑我还注意到您正在对正在读取的行数进行硬编码,除非您知道文件的格式,否则我不会这样做。
fscanf( "%c", ... )
仅扫描一个字符(例如'5')。 通过减去“ 0”,可以从字符'5'
获得整数值5
。 您可以使用"%d"
扫描仅包含数字(不包括格式字符)的整数,或使用"%f"
扫描浮点数(不确定将56.154
读取为“ 56 000 154”(欧洲大陆)还是使用“ 56加154/1000英寸(GB /美国)(世界其他地区:我只是不知道,不要被冒犯)
printf( "\\n", ... )
:您忘记使用任何格式字符串,例如%d
(int), %f
(float)...因此,仅换行符本身,将不会打印您的参数。
int** mat=malloc(1000000*sizeof(int));
您正在这里分配一个int *
数组,因此它应该是int** mat=malloc(1000000*sizeof(int *));
编辑:我再次查看了您的文本文件,并看到了不能格式化整数的数字,例如98.54。 所以这是很清楚,你需要float
或double
,而是如果int
为您的数组,并使用"%f"
为float
或"%lf"
的double
两个fscanf()
和printf()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.