I am trying to read in numbers from a text file for an NxN matrix and 1xN matrix using fscanf
. I know this question has been asked here before, but I have tried the solutions and simply cannot understand why my method does not work. The NxN matrix is:
1 1 1
3 1 0
-1 0 1
and the 1xN matrix is:
6
11
-2
The numbers in the rows are separated by one space and the columns are separated by \n
. This is my code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int countlines(FILE *f);
void reduce_mat(double **matrix, double *vector, int row, int column);
void swapping(double **matrix, double *vector, int row, int column);
int main()
{
FILE *f1=fopen("matrix.txt","r");
FILE *f2=fopen("vector.txt","r");
int dim_matrix=countlines(f1);
int dim_vector=countlines(f2);
//allocate memory for matrix and vector
double **Mat_A=(double **) malloc(dim_matrix*sizeof(double));
for(int j=0; j<dim_matrix; j++)
Mat_A[j]=(double *) malloc(dim_matrix*sizeof(double));
double *Vec_B=(double *) malloc(dim_vector*sizeof(double));
//read in numbers from file
for(int i=0; i<dim_matrix; i++)
for(int j=0; j<dim_matrix; j++)
{
fscanf(f1,"%lf",&Mat_A[i][j]);
printf("Mat_A[%d][%d]=%lf\n",i,j,Mat_A[i][j]);
}
for(int k=0; k<dim_vector; k++)
{
fscanf(f2, "%lf", &Vec_B[k]);
printf("Vec_B[%d]=%lf\n",k,Vec_B[k]);
}
int countlines(FILE *f)
{
//check if file exists
if (f==NULL)
{
printf("File does not exist");
return 0;
}
int count=0; //intialize the count
char c; //place to store characters from file
for (c=getc(f); c!=EOF; c=getc(f))
{
if (c=='\n')
{
count+=1;
}
}
return count;
}
And it just prints out zeroes for every value. I have tried to use "%lf%[\n]%"
, "%lf%"
, etc. I simply can't figure out where I am going wrong, as this implementation seems to work for other people.