https://rentry.org/PPP2_p188

// Code derived from Stroustrup's PPP2 book
// § 6.4 Grammars
//  -and beginning on p 188

#include <iostream>
#include <stdexcept>
#include <vector>

using std::cerr;
using std::cin;
using std::cout;
using std::exception;
using std::runtime_error;
using std::vector;

void error(const char* s) { throw runtime_error(s); }

// a simple user-defined type
class Token {
 public:
  Token(char ch) : kind{ch} {}

  Token(char ch, double val) : kind{ch}, value{val} {}

  char   kind  = '0';
  double value = 0.0;
};

Token get_token()
{
  char ch;
  cin >> ch;  // note that >> skips whitespace (space, newline, tab, etc.)

  // clang-format off
  switch (ch) {
    case ';':
    case '+':
    case '-':
    case '*':
    case '/': return Token{ch};  // let each character represent itself
    case '.':  // a floating-point literal can start with a dot
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9': {  // numeric literal
      cin.putback(ch);  // put digit back into the input stream
      double val;
      cin >> val;  // read a floating-point number
      return Token{'8', val};
    }
    default: error("Bad token");
  }
  // clang-format on

  // shouldn't reach here
  return Token{'K'};
}

vector<Token> toks;  // we'll put the tokens here

int main()
try {
  cout << "Please enter expression (we can handle +, –, *, and /),\n";
  cout << "  then add a ; to print (e.g., 1+2*3;): \n";

  while (cin) {
    Token t = get_token();
    if (t.kind == ';')
      break;

    toks.push_back(t);
  }

  // print Token contents out to console:

  cout << "\nthe Tokens are listed as:\n"
       << " t.kind  :  t.value \n";

  for (Token t : toks)
    cout << "      " << t.kind << "  :  " << t.value << '\n';

} 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_p188.cpp && ./a.out

PrevUpNext

Edit
Pub: 14 Mar 2023 14:08 UTC
Edit: 30 Apr 2023 11:11 UTC
Views: 339