Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read from text file and store in matrix in c

Tags:

c

text

matrix

the first to say is that I'm totally new to coding, so plz forgive my mistakes. I'm now trying to read from a txt file which is rather large, it has about 1000000 lines and 4 cols

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
........
........

I want to read them all and store them into a matrix, here is my code:

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

The result is that I got nothing in my matrix. I hope u can help. Thanks in advance for any help.


like image 520
rooooookie Avatar asked Aug 13 '13 17:08

rooooookie


2 Answers

Many Issues, consider following, and of course see comments

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);
}
like image 76
P0W Avatar answered Nov 03 '22 06:11

P0W


  1. fscanf( "%c", ... ) only scans one single character (e.g. '5'). By subtracting '0' you get the integer value 5 from the character '5'. You can use "%d" to scan integers that consist only of digits (not including formatting characters), or "%f" for floats (not sure if 56.154 is to be read as "56 thousand 154" (continental europe) or "56 plus 154/1000" (GB / USA) (the rest of the world: don't be offended I just don't know)

  2. printf( "\n", ... ): you forgot to use any formatting string such as %d (int), %f (float) ... So your parameter will not be printed, just the newline itself.

  3. int** mat=malloc(1000000*sizeof(int)); You're allocating an array of int * here, so it should be int** mat=malloc(1000000*sizeof(int *));

Edit: I've looked again at your text file and have seen numbers like 98.54 that can't be formatted integers. So it's quite clear you will need float or double instead if int for your array and use "%f" for float or "%lf" for double in both fscanf() and printf()

like image 31
Ingo Leonhardt Avatar answered Nov 03 '22 07:11

Ingo Leonhardt