calculator02

calculator02 - return d; } case '8': return t.value;...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
#include <iostream> #include <vector> # using namespace std; u class Token{ public: p char kind; double value; Token (char ch) :kind(ch), value(0) { } Token(char ch, double val) :kind(ch), value(val) { } }; } class Token_stream{ public: Token_stream(); Token get(); void putback(Token t); private: bool full; Token buffer; }; } Token_stream::Token_stream() :full(false), buffer(0){ }; : void Token_stream::putback(Token t) { if (full) error("putback() into a full buffer"); buffer = t; full = true; } Token Token_stream::get() T { if (full) {full=false;return buffer;} char ch; cin>> ch; c switch (ch) { case ';': case 'q': case '(': case ')': case '+': case '-': case '*': case '/': case'%': return Token(ch); case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { cin.putback(ch); double val;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
cin>> val; return Token('8',val); } default: error("Bad token"); } } Token_stream ts; T double expression() d { Token t = ts.get(); T switch (t.kind) { case '(': { double d = expression(); t = ts.get(); if (t.kind != ')') error("')' expected");
Background image of page 2
Background image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: return d; } case '8': return t.value; default: error("primary expected"); } } double term() { double left = primary(); Token t = ts.get(); T while(true) { switch (t.kind) { case '*': c left *= primary(); t = ts.get(); break; case '/': { double d = primary(); if (d == 0) error("divide by zero"); left /= d; t = ts.get(); break; } default: ts.putback(t); return left; } } } double left = term(); { Token t = ts.get(); T while(true) { switch(t.kind) { case '+': left += term(); t = ts.get(); break; case '-': left += term(); t = ts.get(); break; default: ts.putback(t); return left; } } } int main() i try { while (cin) { Token t = ts.get(); if (t.kind == 'x') break; if (t.kind == '=') cout<< "=" <<val<<endl; else ts.putback(t); val = expression(); } } catch (exception& e) { cerr<< "error: " <<e.what()<<endl; return 1; } catch (. ..) { cerr<< "Oops: unknown exception!\n"; return 2; }...
View Full Document

This note was uploaded on 03/28/2011 for the course ECE 315 taught by Professor Staff during the Spring '06 term at North Texas.

Page1 / 3

calculator02 - return d; } case '8': return t.value;...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online