https://rentry.org/PPP2_p180

// 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

PrevUpNext

Edit
Pub: 13 Mar 2023 04:20 UTC
Edit: 30 Apr 2023 07:24 UTC
Views: 434