gpt4 book ai didi

c - 如何从文本文件中读取并存储在c中的矩阵中

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:32 25 4
gpt4 key购买 nike

首先要说的是我对编码完全陌生,所以请原谅我的错误。我现在正在尝试从一个相当大的 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);
}

结果是我的矩阵中什么也没有。我希望你能帮忙。在此先感谢您的帮助。


最佳答案

很多Issue,考虑关注,当然也看评论

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

关于c - 如何从文本文件中读取并存储在c中的矩阵中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18215325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com