Add quoted string literals, e.g.: "str" or 'str'

This commit is contained in:
Vinícius Garcia
2016-04-20 13:05:05 -03:00
parent 229420f205
commit ebdaaa13a7
2 changed files with 27 additions and 0 deletions

View File

@@ -9,6 +9,7 @@
#include <math.h>
#include "shunting-yard.h"
#include "shunting-yard-exceptions.h"
OppMap_t calculator::buildOpPrecedence() {
OppMap_t opp;
@@ -81,6 +82,28 @@ TokenQueue_t calculator::toRPN(const char* expr,
rpnQueue.push(new Token<std::string>(key, VAR));
}
lastTokenWasOp = false;
} else if(*expr == '\'' || *expr == '"') {
// If it is a string literal, parse it and
// add to the output queue.
char quote = *expr;
++expr;
std::stringstream ss;
while(*expr && *expr != quote && *expr != '\n') {
if(*expr == '\\') ++expr;
ss << *expr;
++expr;
}
if(*expr != quote) {
std::string squote = (quote == '"' ? "\"": "'");
throw syntax_error(
"Expected quote (" + squote +
") at end of string declaration: " + squote + ss.str() + ".");
}
++expr;
rpnQueue.push(new Token<std::string>(ss.str(), STR));
lastTokenWasOp = false;
} else {
// Otherwise, the variable is an operator or paranthesis.

View File

@@ -116,6 +116,10 @@ int main(int argc, char** argv) {
assert("str1 + 10 == str4", true, &vars);
assert("10 + str2 == str5", true, &vars);
assert("'foo' + \"bar\" == str3", true, &vars);
assert("'foo' + \"bar\" != 'foobar\"'", true, &vars);
assert("'foo' + \"bar\\\"\" == 'foobar\"'", true, &vars);
std::cout << "\nTesting exception management\n" << std::endl;
assert_throws(c3.eval());