我正在阅读“使用C ++的原理和实践”,我坚持第6章,本书给出了这个例子:
我们如何在计算器中使用代币?我们可以读出输入 代币矢量:
#include <std_lib_facilities.h>
class Token {
public:
char kind;
double value;
Token(char ch = char())
:kind(ch), value(0){}
Token(char ch, double val)
:kind(ch), value(val){}
};
Token get_token(); //read a token from cin
vector<Token> tok; //we'll put the tokens here
int main()
{
while(cin){
Token t = get_token();
tok.push_back(t);
}
}
get_token()
没有定义,我不知道函数体内应该自己定义什么,书中没有提到......
答案 0 :(得分:0)
不知道这本书使用了什么,所以我使用了一本“#”的字符。表示包含数字的令牌(与运算符相对)。还有一个带有&#39; z&#39;表明它已超过所有有效令牌。这里没有错误检查无效输入(不是数字或运算符)。需要在空白行上点击control-d才能结束。
//read a token from cin
Token get_token()
{
string word;
cin >> word;
if ( cin.eof() )
{
Token temp('z');
return temp;
}
if ( word.length() == 1)
{
switch (word[0])
{
case '+':
case '-':
case '/':
case '*':
case '=':
{
Token temp(word[0]);
return temp;
}
default:
{
Token temp('n',stof(word));
return temp;
}
}
}
else
{
Token temp('n',stof(word));
return temp;
}
}
vector<Token> tok; //we'll put the tokens here
int main()
{
cout << "enter an expression to calculate - control-d on blank line to terminate" << endl;
while (cin)
{
Token t = get_token();
tok.push_back(t);
}
}
最后消除非价值代币:
Token t = get_token();
while (cin)
{
tok.push_back(t);
t = get_token();
}
答案 1 :(得分:0)
检查作者的网站以获取完整代码:http://www.stroustrup.com/Programming/calculator00.cpp
get_token()
函数应如下所示:
Token get_token() // read a token from cin
{
char ch;
cin >> ch; // note that >> skips whitespace (space, newline, tab, etc.)
switch (ch) {
//not yet case ';': // for "print"
//not yet case 'q': // for "quit"
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"
}
default:
error("Bad token");
}
}