[英]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.