• C

scanning and printing a matrix from file

Hey. ok, not sure what i'm doing wrong. I'm trying to scan a set of numbers from a file into a matrix and then print the matrix.
Please Help!!!
thanx!

#include <stdio.h>
int main(){
#define SIZE 5
float matrix[5][5];
int a, b;
FILE *fptr;
char name[50];

printf("Please enter a file name--");
scanf("%s", &name);
fptr = fopen(name, "r");
if(fptr==0){
 printf("ERROR\n");
 return 0;
 }

for(a=0;a<SIZE;a++){
 for(b=0;b<SIZE;b++){
     fscanf(fptr,"%f", &matrix[a][b]);
}}
 return 0;
}

///////////////////////////////
//PRINT FUNCTION//

int print(float matrix[5][5]){

#define SIZE 5
float trix[5][5];
int a, b;

for(a=0;a<SIZE;a++){
 for(b=0;b<SIZE;b++){
     printf("%f", trix[a][b]);
}    printf("\n");
}

 return 0;
}


cooling9999Asked:
Who is Participating?
 
ddunleaCommented:
Hi cooling9999,

A couple of things:

First, it's a good idea to put your define statements at the top of the file, before you start defining functions.

Secondly, the code does scan in the matrix correctly, so that's good. But then, it simply returns, so there is no call to the print function. You need to add

for(a=0;a<SIZE;a++){
 for(b=0;b<SIZE;b++){
     fscanf(fptr,"%f", &matrix[a][b]);
}}

print(matrix);
return 0;

On top of that, the print function needs changing. It should read:

int print(float matrix[SIZE][SIZE]){
int a, b;

for(a=0;a<SIZE;a++){
 for(b=0;b<SIZE;b++){
     printf("%f ", matrix[a][b]);
}    printf("\n");
}

Don't use "5" when you have "SIZE" defined. Lastly, don't use the "trix" variable as we want to operate on the "matrix" variable which was passed in. Od, and there needs to be a space after %f to stop the numbers running together.

Cheers!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.