简体   繁体   中英

How to scan through user input and cut it into chunks in c++?

I'm making a program to evaluate conditional proposition (~ or and -> <->). As the users input propositional variables and truth values (true, false) ,and proposition ; the program will go through the inputs and return the truth value for the whole proposition.

  • For ex: if i set p = true , q = true , r = false and input: p or q and r .
  • Is the anyway I can cut it into q and r first, then process and put it back to result (which is false ), then process the next bit ( p or false ) ??. And it has to keep cutting out bits (In proper order of Precedence) and putting them back until I have left is a single true or false .

    • And what I'm I supposed to use to hold user input (array, string) ???

    • Any help would be appreciated ! Thanks.

Tasks like this are usually split into two phases, lexical analysis and syntactic analysis.

Lexical analysis splits the input into a stream of tokens . In your case the tokens would be the operators ~ , or , and , -> , <-> , variables and the values true , false . You didn't mention them but I'd imagine you also want to include brackets as tokens in your language. Your language is simple enough that you could just write the lexical analyser yourself but tools such as flex or ragel might help you.

Synyactic analysis is where you tease out the syntactic structure of your input and perform whatever actions you need (evaluate the preposition in your case). Syntactic analysis is more complex than lexical analysys. You could write a recursive descent parser for this task, or you could use a parser generator to write the code for you. The traditional tool for this is called bison , but it's a bit clunky. I like another simple tool called the lemon parser generator although it's more C orientated than C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM