In this program, I need to get the solutions of a linear system and this system have n variables and n equations. I need to extract the coefficients of the equations in a text file (.txt) and put them on a matrix. The first line of the text file has a number, which is the number of equations in the system. The other lines, have the equations.
For example, if I have the following text file:
3
2x - 3y = 0
4x + z = 12
5y - 6z = 10
The matrix with the coefficients will be:
|2 -3 0 0|
|4 0 1 12|
|0 5 -6 10|
I know how to get the solutions of the linear system, but how can I get only the coefficients of the system (without a library)? I tried functions that only read numbers from a string(vector of char) but they won't work if the coefficient is a letter (return 0) or doesn't exist.
Rules:
The equations of the system need to be LINEAR, otherwise the program will be closed.
If the coefficient and the variable of the equation doesn't exist, the coefficient is 0.
If the coefficient doesn't exist, but the variable exists, (x, y, z for example), the coefficient is 1.
The variable can be any letter, it doesn't need to be x, y and z.
The code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXCHAR 1000
#include "LinkedList.c"
//in the future use STRTOK e SSCANF (SPRINTF maybe)
int main() {
FILE *fp;
char str[MAXCHAR];
int character;
int c = 0;
char fileaddress[50];
char *cp;
char *variaveis;
char *p;
int quant = 0;
int numDeEquacoes = 0;
printf("Enter the address of the file you want to open: ");
gets(fileaddress);
printf(fileaddress);
//int coeficientes[3][3];
fp = fopen(fileaddress, "r");
if (fp == NULL){
printf("\n");
printf("Cannot open file %s",fileaddress);
return 1;
}
printf("\n");
while (fgets(str, MAXCHAR, fp) != NULL)
{
quant++;
if(quant==1)
{
numDeEquacoes = (str[0] - '0');
}
printf("%s", str);
//gets(str, sizeof(str), stdin);
printf("Variables of equation: ");
for(cp=str; *cp; ++cp)
if(isalpha(*cp))
{
printf("%c", *cp, "\n");
//scanf("%c", )
}
//THE CODE THAT RESULTS IN ONLY NUMBERS
while (*p)
{
if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1))) )
{
long val = strtol(p, &p, 10);
printf("%ld\n Coefficients:", val, "\n");
}
else
{
p++;
}
}//ENDS HERE
//printf("Variaveis: ", variaveis);
//printf("\n");
//variaveis = strstr(str);
//printf(variaveis);
}
fclose(fp);
if(quant-1!=numDeEquacoes)
{
printf("The number of equations is wrong!\n");
printf("The number of equations is: %i", numDeEquacoes,"\n");
printf("The variable quant is: %i", quant,"\n");
return 0;
}
//int coeficientes[numDeEquacoes][numDeEquacoes];
//printf("coef:",coeficientes);
return 0;
}