📄 scan_expr.cpp
字号:
#include "eval_expr.h"char nextchar();void retract( char c );// This token uses a state transition diagram to read// tokens from the input: numbers, arithmetic operators,// parentheses, and newlinesint nexttoken( string& tok_str ){ int state = 0; char c; tok_str = ""; while ( true ) { switch( state ) { case 0: c = nextchar(); tok_str += c; switch( c ) { case '+': return TOK_ADD; case '-': // We don't know if this - is for // subtraction or negation; it will // be determined at the syntax // analysis level return TOK_SUB; case '*': return TOK_MUL; case '/': return TOK_DIV; case '(': return TOK_LPAR; case ')': return TOK_RPAR; case '\n': return TOK_EOL; case '.': state = 2; break; case -1: return TOK_EOF; default: if ( isdigit( c ) ) state = 1; else return TOK_ERR; } break; case 1: // This state is used to process a token // that begins with a sequence of digits c = nextchar(); if ( isdigit( c ) ) { tok_str += c; } else if ( c == '.' ) { tok_str += c; state = 2; } else { retract( c ); return TOK_NUM; } break; case 2: // This state is used to process digits after // the decimal point, if any c = nextchar(); if ( isdigit( c ) ) tok_str += c; else { retract( c ); // A decimal point by itself is not // a valid number! if ( tok_str.size() > 1 ) return TOK_NUM; else return TOK_ERR; } } }}// This function puts a previously read character// back into the input stream, so that it will be// the next character to be read. It is useful// when reading tokens that consist of a sequence// of characters whose length is not known in// advance, thus making it necessary to read one// character past the end of the tokenvoid retract( char c ){ cin.putback( c );}// This character reads and returns the next// character in the input. If the read operation// fails, it is assumed that we have reached the// end of the input, and the value -1 (used in C// to signify end-of-file, or EOF) is returned.// Spaces and tabs are skipped, but newlines are// not, because expressions are intended to be// terminated by a newlinechar nextchar(){ char c; do { c = cin.get(); if ( cin == false ) return -1; } while ( c == ' ' || c == '\t' ) ; return c;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -