Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

doitfgts

Name: Anonymous 2011-03-19 2:25

Write a function in C that gets passed a pointer to a null-terminated string containing an arithmetic expression such as "3*(4+5)-1" and returns the correct value.  It must be able to handle +,-,*,/, and parenthesis.  No implied multiplication, no negative numbers, usual order of operations, and the passed string is guaranteed to have matched parenthesis and proper syntax.

Name: Anonymous 2011-03-19 6:33

because boredom.


float asdf(const char *inp_t) {
    char *inp = strdup(inp_t);
    float *arr = (float *)malloc(strlen(inp_t) * sizeof(float));
    unsigned pos=0, c=0;

    while (inp[pos] != 0) {
        switch (inp[pos]) {
            case '+':case '-':case '*':case '/':
                arr[c++] = inp[pos++];
                break;

            case '(': {
                int lpar = pos++;

                for (int t = 1; t > 0; pos++)
                    t += (inp[pos]=='(')-(inp[pos]==')');

                inp[pos-1] = 0;
                arr[c++] = asdf(&(inp[lpar+1]));
                break;
            }
            default: {
                int len = strcspn(&(inp[pos]), "+-*/()");
                char tmp = inp[pos+len];
                inp[pos+len] = 0;
                arr[c++] = atoi(&(inp[pos]));
                inp[pos=pos+len] = tmp;
            }
        }
    }

    if (--c == 0) return arr[0];

    for (int i=1; i<=c-1; i+=2) {
        if (arr[i] == '-') arr[i+1] = -arr[i+1];

        if (arr[i] == '/' || arr[i] == '*') {
            arr[i+1] = arr[i-1]*((arr[i]=='/')/arr[i+1] + (arr[i]=='*')*arr[i+1]);
            arr[i-1] = 0;
        }
    }

    for (int i=c; i>0; i-=2) arr[i-2] += arr[i];

    return arr[0];
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List