From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=0.2 required=5.0 tests=BAYES_00,INVALID_MSGID, REPLYTO_WITHOUT_TO_CC autolearn=no autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 103376,6c3ae0d989a443ef X-Google-Attributes: gid103376,public From: Larry Coon Subject: Re: anyone knows how to do this? Date: 1997/10/27 Message-ID: <345510B6.2A2F@assist.org>#1/1 X-Deja-AN: 285387858 References: <3453D4A2.2264@upnaway.com> Organization: University of California Reply-To: larry@assist.org Newsgroups: comp.lang.ada Date: 1997-10-27T00:00:00+00:00 List-Id: sho wrote: > How do you get an expression from the user and calculate it? like for > example.. the user has to input (1+3/4 rem 4) then calculate the result > Is it possible to get user input in expression like the example above? > If you know how to do it could you please tell me how? Thank you for > your time. Hmmm, there's a right way to do it (write a lexer and parser) and there's probably a simple way of doing it (just chew through the thing and use a stack). The quick way would involve reading a character at a time until you have a "token" (an atomic element such as "+" or "rem"), push the token onto a stack, and when you've consumed all the input, go back through the stack pop each token-op-token, evaluate it, and push the result. Doing this, you need to watch for parens and precedence, so it's not as easy as it looks (most intro programming examples I've seen do this kind of approach but restrict the input to valid postfix expressions). Doing it right is not an easy task. To do it right (precedence rules, parenthesised sub-expressions, etc.), you'd need to write a lexical analyzer (to break the expression into tokens) and use the grammar (in a form such as BNF) to write a parser (a simple operator-precedence parser should do the trick here). The parser ensures that the input is a valid expression and outputs a parse tree, which your program can then do a postorder traversal on to evaluate the expression. If I haven't scared you away yet, look for a book that covers finite state autotoma, BNF, lexers and parsers. There are several such books out there. Avoid the book by Aho, et. al. -- it's the standard reference, but it's too deep for what you're doing. "Introduction to Compiler Construction" by Thomas Parsons is a little easier to read, and though it also goes way deeper than you need (like the Aho book, its subject is writing a compiler, not just parsing and evaluating expressions), it covers everything you need to know. Larry Coon University of California larry@assist.org and lmcoon@home.com