Trending News
Bjarne Stroustrup programming practices and principles chapter 7?
I have a question about logic flow:
I'm trying to create a calculator functionality that:
1.lets you assign a declare a variable (eg, let x = 5;)
2. that will also let you reassign a value (eg, x = 10;)
3. will let you use values in expressions (eg, x + 5; returns 15)
The bottom function statement() is supposed to decide if Token Token_stream::get()
returns a declaration, reassignment, or expression then run the appropriate code.
In having Token Token_stream::get() a return name to statement()
call reassignment and then search for a '=', I lost the functionality to
have an expression() start with a name.
I would have to create special token for assignment to use in statement() if Token Token_stream::get() reads a string followed by a '=', but then put the name back into the input
stream so I can grab if for the assignment. Does any have any suggestions?
//------------------------------------------------------------------------------
Token Token_stream::get()
{
if (full) { full=false; return buffer; }
char ch;
cin >> ch;
switch (ch) {
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
case '%':
case ';':
case '=':
case ',':
return Token(ch);
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{ cin.unget();
double val;
cin >> val;
return Token(number,val);
}
default:
if (isalpha(ch)) {
string s;
s += ch;
while(cin.get(ch) && (isalpha(ch) || isdigit(ch))|| ch =='_' ) s+=ch;
cin.unget();
if (s == "let") return Token(let);
if (s == "const") return Token(constant);
if (s == "q") return Token(quit);
if (s == "sqrt") return Token(square_root);
if (s == "pow") return Token(exponent);
return Token(name,s);
}
error("Bad token");
}
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------
double statement()
{
Token t = ts.get();
switch(t.kind)
{
case let:
return declaration();
case name:
ts.unget(t);
return assigment();
case constant:
return declare_constant();
default:
ts.unget(t);
return expression();
}
}
//----