https://rentry.org/PPP2_p180 ⎗ ✓ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62// Code derived from Stroustrup's PPP2 book // § 6.3.1 First attempt // -and beginning on p 180 #include <iostream> #include <stdexcept> using std::cin; using std::cout; using std::exception; using std::runtime_error; void error(const char* s) { throw runtime_error(s); } int main() try { cout << "Please enter expression (we can handle +, –, *, and /)\n"; cout << "add an x to end expression (e.g., 1+2*3x): \n"; int lval = 0; int rval = 0; cin >> lval; // read leftmost operand if (! cin) error("no first operand"); for (char op; cin >> op;) { // read operator and right-hand operand // repeatedly if (op != 'x') cin >> rval; if (! cin) error("no second operand"); switch (op) { case '+': lval += rval; // add: lval = lval + rval break; case '-': lval -= rval; // subtract: lval = lval – rval break; case '*': lval *= rval; // multiply: lval = lval * rval break; case '/': lval /= rval; // divide: lval = lval / rval break; default: // not another operator: print result cout << "Result: " << lval << '\n'; return 0; } } error("bad expression"); } catch (exception& e) { cerr << "error: " << e.what() << '\n'; return 1; } catch (...) { cerr << "Oops: unknown exception!\n"; return 2; } build & run: g++ -std=c++20 -O2 -Wall -pedantic ./ch_06/main_p180.cpp && ./a.out sauce: Bjarne Stroustrup's PPP2 textbook /robowaifu/'s official C++ learning textbook thread Prev • Up • Next