Reputation: 363
So, I created a matrix on a text file, which looks like this:
1.0#2.2#3.4
3.4#5.5#1.0
6.6#5.5#1.0
I need my script to read each number on the line, add them and then create a new matrix with the result of dividing each number for the sum of the whole line. Example:
1.0+2.2+3.4 = 6.6
The first line of the second matrix that I will create will be:
0.15#0.33#0.51 (because 1.0/6.6 is 0.15 etc.)
Now I can print the whole matrix but I can't get my head on how to save each number of the line as a variable and add it to the next numbers, any suggestion on this?
This is my current work:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr;
double c;
// Open file
fptr = fopen("mat.txt", "r");
if (fptr == NULL) {
printf("Cannot open file \n");
exit(0);
}
// Read contents from file
c = fgetc(fptr);
while (c != EOF) {
printf ("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
return 0;
}
Upvotes: 1
Views: 307
Reputation: 192
Below method uses dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
size_t x = 3, y = 3;
int ret, i, j;
FILE *fptr_in , *fptr_out;
double (*d)[y], sum = 0;
d = malloc( sizeof(double) * x * y );
assert(d != NULL);
// Open file
fptr_in = fopen("mat.txt", "r");
assert(fptr_in != NULL);
/*file to write output*/
fptr_out = fopen("mat_out.txt", "w");
assert(fptr_out != NULL);
for(i = 0; i < x; i++){
sum = 0;
for(j = 0; j < y; j++){
ret = fscanf(fptr_in, "%lf", &d[i][j]);
assert(ret > 0);
sum += d[i][j];
}
for(j = 0; j < x; j++){
ret = fprintf(fptr_out, "%lf ", d[i][j]/sum);
}
fprintf(fptr_out, "\n");
}
free(d);
fclose(fptr_in);
fclose(fptr_out);
return 0;
}
Upvotes: 0
Reputation: 12732
Assuming your matrix
will be of size 3*3
always and #
is the deliminator, in that case you can use fscanf
to read 3 values in while loop like below.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr;
double a=0,b=0,c=0;
double matrix[3][3];
// Open file
fptr = fopen("mat.txt", "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
int i =0;
/*fscanf reads the 3 values each time into a,b and c*/
while (fscanf(fptr,"%lf#%lf#%lf", &a,&b,&c) == 3)
{
double sum = a+b+c;
matrix[i][0] = a/sum;
matrix[i][1] = b/sum;
matrix[i][2] = c/sum;
i++;
}
for (i=0;i<3;i++)
printf ("%lf %lf %lf\n", matrix[i][0],matrix[i][1],matrix[i][2]);
fclose(fptr);
return 0;
}
Upvotes: 2