// First Experience #include #include using namespace std; /***************************************************************************** * 型定義 *****************************************************************************/ /** 内部で使われている値の型 */ typedef int value; /***************************************************************************** * 演算子定義 *****************************************************************************/ #define OP_IMPL(name, op) \ static value op_##name(const value a, const value b) \ { return a op b; } OP_IMPL(add, +) OP_IMPL(sub, -) OP_IMPL(mul, *) /***************************************************************************** * メインルーチン *****************************************************************************/ /** * 代入の大きさチェック * * @param v 入力値 * @return v * @throw エラーメッセージ */ static inline value check_value(const value v) { if(v < 0 || v > 9999) throw "Overflow."; return v; } /** * 計算する。 * * @param s 入力式 * @return 返り値 * @throw エラーメッセージ */ value solve(const string& s) { // レジスタ value r1 = 0, r2 = 0; value (*r3)(const value, const value) = NULL; // ループ #define OPERATOR(func) \ r1 = r3 ? check_value(r3(r1, r2)) : r2, r2 = 0, r3 = func for(int i = 0; i < s.size(); i++) switch(s[i]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': r2 = check_value(r2 * 10 + ((int)s[i] - '0')); break; case '+': OPERATOR(op_add); break; case '-': OPERATOR(op_sub); break; case '*': OPERATOR(op_mul); break; case '=': #ifdef _DEBUG if(i != s.size() - 1) throw "Malformed expression (non-last =)."; #endif//_DEBUG OPERATOR(NULL); return r1; default: throw "An illegal symbol was given."; } throw "Malformed expression. (= does not exist at last)"; } /** * メインルーチン */ int main() { string s; while(getline(cin, s)) try { cout << solve(s) << endl; } catch(const char *_dummy) { #ifdef _DEBUG cerr << "** " << _dummy << endl; #endif//_DEBUG cout << "E" << endl; } return 0; }