carraysinputequations

Taking equations as user input in c


I've been racking my brain at this problem since yesterday and I was hoping someone could point me in the right direction. I'm new to C and we must create a program where the user enters a series of linear equations that must be solved with Cramer's rule. The math is not a problem, however I am not sure how to get the coefficients from an entire equation composed of chars and ints.

The user input should look like a series of linear equations such as:

-3x-3y-1z=6

2x+3y+4z=9

3x+2y+4z=10

This would be simple if we were allowed to only enter the coefficients but sadly the whole equation must be entered. You can assume that there are no spaces in the equation, the order of variables will be the same, and that the equations are valid.

I was thinking about storing the whole equation in an array and searching for each variable (x,y,z) then finding the int before the variable, but I cannot determine a way to convert these found variables into integers.

Any help is greatly appreciated. Thanks in advance.


Solution

  • //ax+bx+cz=d, -999 <= a,b,c,d <= 999
    int a, b, c, d, i ,j;
    char A[5], B[5], C[5], D[5], str[22];
    char *pntr;
    
    printf("Enter equation: ");
    fgets(str, 21, stdin);
    
    pntr = A;
    i = j = 0;
    while(1){
        if(str[i] == 'x'){pntr[j] = '\0'; pntr = B; j = 0; i++; continue;}
        else if(str[i] == 'y'){pntr[j] = '\0'; pntr = C; j = 0; i++; continue;}
        else if(str[i] == 'z'){pntr[j] = '\0'; pntr = D; j = 0; i += 2; continue;}
        else if(str[i] == '\n' || str[i] == '\0'){pntr[j] = '\0'; break;}
    
        pntr[j] = str[i];
    
        i++;
        j++;
    }
    
    a = atoi(A);
    b = atoi(B);
    c = atoi(C);
    d = atoi(D);
    
    printf("%d %d %d %d \n", a, b, c, d);
    

    valter