Chapter 6

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: break; case '/': left /= primary(); break; default: return left; // return the value return // return } } } Stroustrup/Programming 21 Dealing with divide by 0 Dealing double term() // exactly like expression(), but for * and / // exactly { double left = primary(); // get the Primary double get while (true) { Token t = get_token(); // get the next Token // get switch (t.kind) { case '*': left *= primary(); break; case '/': { double d = primary(); if (d==0) error("divide by zero"); left /= d; break; } default: return left; // return the value // return } } Stroustrup/Programming } 22 Dealing with numbers and parentheses Dealing double primary() // Number or ‘(‘ Expression ‘)’ double // Number { Token t = get_token(); switch (t.kind) { case '(': // handle ‘(’expression ‘)’ handle { double d = expression(); t = get_token(); if (t.kind != ')') error("')' expected"); return d; } case '8': // we use ‘8’ to represent the “kind” of a number // we return t.value; // return the number’s value // return default: error("primary expected"); } } Stroustrup/Programming 23 Program organization Program Token error() get_token() primary() term() istream cin >> ostream cout << expression() main() Who calls who? (note the loop) (note Who Stroustrup/Programming 24 The program The #include "std_lib_facilities.h" // Token stuff (explained in the next lecture) // Token double expression(); // declaration so that primary() can call expression() double expression() double primary() { /* … */ } double double term() { /* … */ } double double expression() { /* … */ } double // deal with numbers and parentheses // deal // deal with * and / (pity about %) deal // deal with + and – deal int main() { /* … */ } int // on next slide // on Stroustrup/Programming 25 The program – main() The int main() try { while (cin) cout << expression() << '\n'; cout keep_window_open(); // for some Windows versions // for } catch (runtime_error& e) { cerr << e.what() << endl; keep_window_open (); return 1; } catch (…) { cerr << "exception \n"; keep_window_open (); return 2; } Stroustrup/Programming 26 A mystery mystery 2 3 4 2 5+6 5 X Bad token an answer an answer an answer (finally, an expected answer) Stroustrup/Programming 27 A mystery mystery 1 2 3 4+5 6+7 8+9 10 1...
View Full Document

This note was uploaded on 02/18/2012 for the course CSCE 121 taught by Professor Walter daugherity during the Fall '09 term at Texas A&M.

Ask a homework question - tutors are online