Very simple two-operand expression 'parser'

tux4life 0 Tallied Votes 174 Views Share

This program can solve expressions of the following forms: a+b , a-b , a*b , a/b ( a and b are numbers :P)
Notice: You can't put spaces in between the operands and the operator, I know this is a limitation and that there are thousands of other ways to achieve a better result, so please don't start complaining about this, it's just a "very simple" two-operand expression 'parser' :)

#include <stdio.h>

int calc(int op1, int op2, char op);
short op_v(char op);

int main(void)
{
    /* Variable declarations */
    char op;
    int op1, op2;
    
    /* Get the expression */
    printf("%s", "Enter a simple expression: ");
	
    /* Break the expression down into tokens and solve it */
    if(scanf("%d%c%d", &op1, &op, &op2) == 3 && op_v(op))
	printf("%s%d", "Result= ", calc(op1, op2, op));
    else
	printf("%s", "Invalid expression.\n");
    
    return 0;
}

/* Calculate the result */
int calc(int op1, int op2, char op)
{
    switch(op)
    {
    case '+': return op1+op2;
    case '-': return op1-op2;
    case '*': return op1*op2;
    case '/': return op1/op2;
    }
}

/* Validate the operator */
short op_v(char op)
{
    switch(op)
    {
    case '+': return 1;
    case '-': return 1;
    case '*': return 1;
    case '/': return 1;
    default: return 0;
    }
}
ddanbe 2,724 Professional Procrastinator Featured Poster

I will not complain. This is very good to start with, but if you like this sort of things, please try to learn more about it! That is if you can and if you want to. It can be a very exciting journey!

tux4life 2,072 Postaholic

The op_v function can be updated, by using strchr instead.
This will compact the code with 13 lines :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.