Click here to Skip to main content
15,885,878 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
i wish to read a matrix from a external file but i just don't know that , please help me , i got this code, and the output doesn't is the output that i'm expected
C#
#include <stdio.h>
#include <stdlib.h>

/*
 *
 */



int main(int argc, char** argv) {

 FILE * f;
 int i,j,dimension=5;
 int  adjacency [dimension][dimension];
f = fopen("adjacency.dat", "r");
for(i = 0; i < dimension ; i++){
    for(j = 0; j < dimension; j++){
        fscanf(f, "%d", &adjacency[i][j]);
        }
    }
fclose(f);

printf("matriz de adyacencia \n");

for (i=0;i<dimension;i++){
    for(j=0;j<dimension;j++)
        printf("%d",adjacency[i][j]);
    printf("\n");
}
    return (EXIT_SUCCESS);
}
Posted

1 solution

The code should not even compile let alone do anything as expected :)
The first thing is the array declaration. This:
int  adjacency [dimension][dimension];

should give an error ('expected constant expression' or something like that). If you want to be able to change the size of the array you can either use a define:
#define DIM 5
...
int adjacency [DIM][DIM];

or use the 'new' operator to create the array.

As for the file reading - you should probably post the contents of the file - otherwise there's no way to know what you are trying to read.

I would also suggest checking if the file was oppened correctly before reading anything...
if( f != NULL )
 
Share this answer
 
Comments
rsuez93 5-May-11 2:03am    
I fixed it all , the problem is the output, i have a problem on the read's data from the file ( which have a 3*3 matriz of numbers
tolw 5-May-11 2:26am    
Can you post the file contents? Just to see what you are dealing with.
Also if the file has a 3x3 matrix of numbers and the array is 5x5 as in your example - you have too few numbers
rsuez93 5-May-11 2:33am    
the file is matriz.txt wich contains a 3x3 matriz : 123
456
789

i want to read these values and stored in a program's matrix, i don't know if the error thah i have it's cuz is there an error when the program reads the file, the thing it's that

when the program runs, the output matrix it's just like this: 1234562425235626
4223523532562632
tolw 5-May-11 2:48am    
Are the values space separated? If not than the first number read would be 123 instead of 1... You should try debbuging to look at the array contents - what's the first number you read?

Try putting this into your file:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

EDIT: Also, try setting the array cells to 0 before reading anything:
memset( array, 0, sizeof( array) );

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900