"Programming Principles and Practice Using C++"
!
基本上我有一个令牌解析器。它一次从cin读取一个字符。它的目的是对5*3+1这样的表达式进行标记,效果很好。其中一个练习是添加一个sqrt()函数。因此,我修改了标记化代码以检测“sqrt()”,然后返回一个表示sqrt的Token对象。在这种情况下,我使用char'。这是其他人会这样做的吗?如果我需要实现sin()怎么办?案情陈述会变得混乱。
char ch;
cin >> ch; // Note that >> skips whitespace (space, newline, tab, etc.)
switch (ch) {
case ';': // For "print"
case 'q': // For "quit"
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
case '!':
return Token(ch); // Let each character represent itself
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
cin.putback(ch); // Put digit back into the input stream
double val;
cin >> val; // Read a floating-point number
return Token('8', val); // Let '8' represent "a number"
}
case 's':
{
char q, r, t, br;
cin >> q >> r >> t >> br;
if (q == 'q' && r == 'r' && t == 't' && br == '(') {
cin.putback('('); // Put back the bracket
return Token('s'); // Let 's' represent sqrt
}
}
default:
error("Bad token");
}