// The calculator from Class 12, + and - only, with pointers. There is one
// function for each layer of an expression such as 12+34-5:
//
//   read_sum      numbers joined by + and -   12 + 34 - 5
//   read_number   one number                  12
//
// Each hands back two things, the way A5's divide does: an outcome as its
// return value, and the value itself through a pointer. Each is also given the
// position in the line as a pointer, int * i, so when it moves past what it
// read, its caller's position moves with it. calculate starts the position at
// 0 and checks that the sum used up the whole line, and only main prints.
// * and / need one more layer, between the two.
//
//   gcc -Wall calc-pointers-basic.c -o calc-pointers-basic
//   ./calc-pointers-basic < exprs.txt          or type expressions, then Ctrl-D

#include <stdio.h>
#define SIZE 100

// the outcomes the functions below return
#define FOUND 1      // a value, in the variable the pointer points to
#define MALFORMED 0  // the line is not an expression

// returns FOUND if a digit is at line[*i], with the number that starts there in
// *number and *i moved past it; returns MALFORMED if not
int read_number(char line[], int * i, int * number) {
    if (line[*i] < '0' || line[*i] > '9') {
        return MALFORMED;
    }
    *number = 0;
    while (line[*i] >= '0' && line[*i] <= '9') {
        *number = *number * 10 + (line[*i] - '0');
        *i = *i + 1;
    }
    return FOUND;
}

// returns FOUND with the value of the numbers joined by + and - at line[*i] in
// *sum, and *i moved past them; returns MALFORMED if a number is missing
int read_sum(char line[], int * i, int * sum) {
    int outcome = read_number(line, i, sum);
    if (outcome != FOUND) {
        return outcome;
    }
    while (line[*i] == '+' || line[*i] == '-') {
        char op = line[*i];
        *i = *i + 1;
        int number;
        outcome = read_number(line, i, &number);
        if (outcome != FOUND) {
            return outcome;
        }
        if (op == '+') {
            *sum = *sum + number;
        } else if (op == '-') {
            *sum = *sum - number;
        } else {
            return MALFORMED;
        }
    }
    return FOUND;
}

// returns FOUND with the value of the expression in line in *value; returns
// MALFORMED if it has none, or if anything is left after it
int calculate(char line[], int * value) {
    int i = 0;
    int outcome = read_sum(line, &i, value);
    if (outcome != FOUND) {
        return outcome;
    }
    if (line[i] != '\0') {
        return MALFORMED;
    }
    return FOUND;
}

int main() {
    char line[SIZE];
    int value;
    while (scanf("%99s", line) == 1) {
        if (calculate(line, &value) == FOUND) {
            printf("%d\n", value);
        } else {
            printf("malformed expression\n");
        }
    }
}
