c - Storing integers from a text file into an integer array -


i have problem exercise, statement following:

  • save matrix name matriu[7][10], getting numbers file.

here text of file: matrix.txt

 1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,0 ,1 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,0 ,0 ,1 ,0 ,0 ,0 ,1 ,0 ,1 ,1 ,0 ,0 ,0 ,1 ,0 ,1 ,0 ,0 ,1 ,1 ,0 ,0 ,0 ,0 ,1 ,0 ,0 ,0 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 , 

following version did, fails. can me fix?

int main() {     int i;     char linea[3024];     int j;     file* file;     file = fopen("matriu.txt", "r");     int matriu[7][10];      while (fgets(linea, sizeof(linea), file) != null) {          char* token;          token = strtok(linea, ",");          printf("%s\n", token);          while (token != null) {              token = strtok(null, ",");              if (token != null)                  matriu[i][j] = atoi(token);              printf("%s\n", token);         }     }      (i = 0; < 7; i++) {         (j = 0; j < 10; j++) {             printf("%d\n", matriu[i][j]);         }     }      return 0; } 

i've saved matrix reading 1 character @ time.

  • if scanned character either '0' or '1' , save matriu[7][10] matrix/array.

  • else scan next character.

here code used perform above actions :

for(i=0;i<7;i++) {     for(j=0;j<10;j++)     {                 {             // i've declared character ch read each character             ch=getc(file);         }while(ch!='0' && ch!='1');          matriu[i][j]=(ch-'0');//converting char integer     } } 

i hope understand above code, code :

#include <stdio.h>   int main() {     int i,j,matriu[7][10];     char ch; //the character      file * file;     file=fopen("matriu.txt", "r");      for(i=0;i<7;i++) //the mechanism     {         for(j=0;j<10;j++)         {                         {                 ch=getc(file);             }while(ch!='0' && ch!='1');             matriu[i][j]=(ch-'0');         }     }      (i=0; i<7; i++)     {         (j=0; j<10; j++)         {             printf("%d\n", matriu[i][j]);          }     }     fclose(file); //you forgot in code     return 0;  } 

it worked desired, , lastly

note: forgot close file pointer in code


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -