Lab 2: Your first Flex program

  1. How to use STL stack?
    #include <stdio.h>
    #include <stack>
    #include <string>
    
    using namespace std;
    
    int main(void) {
        stack<string> s;
    
        s.push("1");
        s.push("2");
        s.push("3");
        s.push("4");
    
        while (!s.empty()) {
    	printf("%s\n", s.top().c_str());
    	s.pop();
        }
    }
    
  2. A Flex example
    %{
    
    /*
     * lab2.l
     *
     * To compile, do the following:
     *   $ flex -t lab2.l > lab2.cc && g++ -g lab2.cc -o lab2 -lfl
     *
     * To run, do the following:
     *   $ lab2 < Factorial.java
     */
    
    #include <stdio.h>
    
    %}
    
    %x  COMMENT
    ws  [ \t]+
    
    %%
    
    "/*" {
        BEGIN COMMENT;
    }
    
    <COMMENT>"*/" {
        BEGIN INITIAL;
    }
    
    <COMMENT>.|\n {
        // Ignore all comments
    }
    
    [A-Za-z0-9_]+ {
        printf("[%s]\n", yytext);
    }
    
    {ws} {
        // Ignore white spaces
    }
    
    .|\n
    
    %%
    
    int main(void) {
        yylex();
        return (0);
    }
    
  3. Some Infix to Postfix notation examples (not in particular order)