Seriously What's wrong in my code

Please check the requirement, you should not use scanf instead, using sscanf cos the input is whole expression such 50 * 40 * 250 + 791 =. You can create a simple parser as below code to walkthrough whole expression.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char ch = 0;
    int state = 0;
    char buff[128];
    char ops = 0;
    unsigned int result = 0;
    int i = 0, idx = 0;

    char expr[1024];
    int cnt = 0;

    if (scanf("%[^=]=%n", expr, &cnt) <= 0)
        return 0;

    while(idx < cnt) {
        ch = expr[idx++];

        printf("state %d ch %c\n", state, ch);
        switch(state) {
            case 0:
                if ((ch <= '9') && (ch >= '0')) {
                    state++;
                    buff[i++] = ch;
                }

                break;
            case 1:
                if ((ch <= '9') && (ch >= '0')) {
                    buff[i++] = ch;
                } else {
                    buff[i] = '\0';
                    if (i > 0) {
                        unsigned int num = atoi(buff);

                        switch (ops) {
                            case '-':
                                result -= num;
                                break;

                            case '+':
                                result += num;
                                break;

                            case '*':
                                result *= num;
                                break;

                            case "https://stackoverflow.com/":
                                result /= num;
                                break;

                            default:
                                result = num;
                                break;
                        }

                        printf("> found fact %d, result %u\n", num, result);
                    }

                    i = 0;

                    if ((ch == '-') || (ch == '+') || (ch == '*') || (ch == "https://stackoverflow.com/")) {
                        state = 0;
                        ops = ch;
                        printf("> found ops %c\n", ch);
                    } else if ((ch == ' ') || (ch == '\t')) {
                        continue;
                    } else if (ch == '=') {
                        break;
                    } else {
                        // expression end
                        break;
                    }
                }

                break;

            default:
                break;
        }
    }

    printf("> result '%u' ", result);

    return 0;
}

Leave a Comment