/* example program to illustrate all the syntax: { n = read; if n < 0 then print "bad" else { f = 1; i = 1; while i <= n do { f = f * i; i = i + 1 } print f } } next_symbol performs lexical analysis, returning a string that represents the next lexeme in the input. To simplify future tasks, some lexemes are decorated with an extra first character: numbers start with # reserved words (if, while, etc) begin with @ strings begin with " but do not have a " at the end @eof represents end of file (on keyboard type ctrl-D) @bad represents an incorrect lexeme everything else is left as it is in this language := is used for assignment and == for equality test <> (less than or greater than) is for inequality test and, or, and not are used instead of &&, ||, and ! */ #include #include #include using namespace std; string next_symbol(istream & in) { char c; while (true) { c = in.get(); if (in.fail()) return "@eof"; if (c > ' ') break; } if (c == '{') return "{"; else if (c == '}') return "}"; else if (c == '(') return "("; else if (c == ')') return ")"; else if (c == ';') return ";"; else if (c == '+') return "+"; else if (c == '-') return "-"; else if (c == '*') return "*"; else if (c == '/') return "/"; else if (c == '%') return "%"; else if (c == '<') { c = in.peek(); if (c == '=') { in.get(); return "<="; } else if (c == '>') { in.get(); return "<>"; } else return "<"; } else if (c == '>') { c = in.peek(); if (c == '=') { in.get(); return ">="; } else return ">"; } else if (c == '=') { c = in.peek(); if (c == '=') { in.get(); return "=="; } else return "@bad"; } else if (c == ':') { c = in.peek(); if (c == '=') { in.get(); return ":="; } else return "@bad"; } else if (c == '"') { string s = "\""; while (true) { c = in.get(); if (in.fail()) return "@bad"; if (c == '"') break; s += c; } return s; } else if (c >= '0' && c <= '9') { string s = "#"; while (true) { s += c; c = in.peek(); if (c < '0' || c > '9') break; in.get(); } return s; } else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { string s = ""; while (true) { if (c >= 'A' && c <= 'Z') s += (char)(c -'A' + 'a'); else s += c; c = in.peek(); if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_') in.get(); else break; } if (s == "if" || s == "while" || s == "then" || s == "do" || s == "else" || s == "print" || s == "read" || s == "and" || s == "or" || s == "not") return string("@") + s; else return s; } else return "@bad"; } int main() { string s; while (true) { s = next_symbol(cin); cout << s << "\n"; if (s == "@eof") break; } }