Reputation: 67
I'm working on a program that reads linear equations from a file such as those - and solve them using matrices:
3x+2y-2z=9
-2x+9y+12z=23
4x-7y+9z=45
The file is supposed to contain n equations with n variables. How to get only the numbers and the signs from the above equations to store in 2d dynamic array of integers?
So output will be something like this:
3 2 -2 9
-2 9 12 23
4 -7 9 45
Upvotes: -1
Views: 687
Reputation: 13796
Using fscanf
, the 'd' modifier handles signed integer, that means it will take care of the input number whether it has +
or -
in front of it, try following code:
#include <stdio.h>
int main(void) {
int x, y, z, e;
FILE *fp = fopen("eq.txt", "r");
if (!fp)
return 1;
while (fscanf(fp, "%dx%dy%dz=%d", &x, &y, &z, &e) == 4) {
printf("%d %d %d %d\n", x, y, z, e);
}
return 0;
}
It outputs for the file you posted:
3 2 -2 9
-2 9 12 23
4 -7 9 45
Upvotes: 1