Reputation: 165
Okay so my assignment is to create a program which reads an unknown nxn matrix from a file and then calculates it's determinant in a certain way. I'm pretty much done except the numbers seem to be jumbling up after getting them from the file.
It's probably easier if you just look at my code, this is the portion up until just after reading the matrix, the values as I said are all jumbled up. It's not the i <= dim because dim counts from 0 so it should run the correct number of times.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
FILE *input;
int i, j, temp;
int dim=0;
double det;
const char inp_fn[]="matrix.dat";
/*Open File*/
input = fopen(inp_fn, "r");
/*Find the number of lines and hence dimensions*/
while (EOF != (temp = fgetc(input)))
{
if (temp=='\n')
{
++dim;
}
}
/*Reset pointer to beginning of file and float the matrix*/
fseek(input, 0, SEEK_SET);
float matrix[dim][dim];
/*Check file isn't NULL, if good fill the matrix with the values from the file*/
if( (input != (FILE*) NULL) )
{
for(i=0; i<=dim; i++)
{
for(j=0; j<=dim; j++)
{
fscanf(input, "%f", &matrix[i][j]);
}
}
fclose(input);
}
else
{
printf("Could not open file!\n");
}
So yer if you guys can see anything please tell me, I'm really new to this so i'm probably missing something obvious, thanks.
Upvotes: 0
Views: 230
Reputation: 11058
Your loops do not match dimensions of the array.
Either your file doesn't have '\n' after the last line, and then you have matrix of (dim+1)*(dim+1)
and should define it as float matrix[dim+1][dim+1]
, or the file has '\n' after the last line, and then you should use i < dim
and j < dim
in loops.
Upvotes: 2