0

So I'm really new to C and I'm fiddling around trying to get some small programs to work. At the moment I am working on a program that simply lets a user input a linear equation and prints it out. It should be able to differentiate between the coefficients and the Variables / Operators so that I can use it later.

My problem is that I don't know of a proper way to scan the input and the solution I have right now seems rather janky:

#include <stdio.h>
#include <math.h>

// a+b+c+d+[...]=n
double Numbers[9]; //Storing the coefficients
char Variable[9]; //Space for storing different variables
char Operator[9]; //Space for storing different operators

int main()
{
    printf("Enter your linear equation:\n");
    int n = 0; //Index value for the arrays
    do
    {
        scanf("%lf", &Numbers[n]);
        scanf(" %c", &Variable[n]);
        scanf(" %c", &Operator[n]);
        n++;
    } while (Operator[n-1] != '='); //Stops as soon as a '=' has been recognized, which signals the end of the equation
    scanf("%lf", &Numbers[n]); //scans for the last number after the '='

    int NumVar = n; //Stores the total number of variables
    while (n > 0) 
    {
        printf("%f%c%c", Numbers[NumVar - n], Variable[NumVar - n], Operator[NumVar - n]); //Substracting 'NumVar' from 'n' 
        n--;
    }
    printf("%f", Numbers[NumVar]);
    
    return 0;
}

PS: pls keep in mind that I am very new to pointers

Shiina
  • 1
  • 2
  • I think I see what you're trying to do, but it would help if you showed your expected input and output. Also: is it working as you expect? Are you asking for help getting it to work, or looking for suggestions on how to make it better? – Steve Summit Sep 16 '22 at 16:54
  • @SteveSummit I want to input a linear equation like 5x+3y-7z=10 for example and for now just print it out (expected output would be 5.000000x+3.000000y-7.000000z=10.000000) it should work for equations using only 1 variable and also more (like 5x-4y+3z+3a-6u-2[...]=55). For now it is working as expected, but it feels like a solution that is problematic and could be solved more elegantly and safer. – Shiina Sep 16 '22 at 17:12
  • I agree it's problematic, largely because of `scanf`. `scanf` is quick'n'easy to use, but it doesn't deal well with malformed inputs. If someone gives you something like `5ab+6cd`, or makes a mistake and types something like `5x + + 6y`, you're doomed. You can [do better than `scanf`](https://stackoverflow.com/questions/58403537), but it's kind of an open-ended problem, and how hard you choose to work on it will depend on how interested you are in writing parsing code, versus writing code to evaluate linear equations. – Steve Summit Sep 16 '22 at 18:16

0 Answers0