The purpose of the code below is to return the tokens of a given expression, for example: 50 + 30 * (30-10) + (10/2) . Where tokens would be: [number, 50], [sum, +], [number, 30], [mult, *], and so on.
However, when you try to return the Token object, which contains the type ( enum
) and the token value requested via getToken (), the following error:
[Error] could not convert '(std :: basic_stringstream str () const with _CharT = char; _Traits = std :: char_traits; _Alloc = std :: allocator; std :: basic_stringstream < _CharT, _Traits, _Alloc & :: :: string_type = std :: basic_string, (operator new (16ull), (, (')'))) 'From' Token * 'to' Token '
main.cpp
#include <iostream>
#include "Scanner.h"
#include "Token.h"
#include <cstdlib>
int main() {
Scanner* scan = new Scanner("48 + 20 * 2");
Token tk = scan->getToken();
while(tk != NULL){
cout<<tk.print()<<endl;
tk = scan->getToken();
}
return 0;
}
Scanner.h
#ifndef SCANNER_H
#define SCANNER_H
#include <string>
#include <iostream>
#include <ctype.h>
#include <sstream>
#include "Token.h"
using namespace std;
class Scanner
{
public:
Scanner(string exp);
Token getToken();
private:
string expressao;
int posicao;
};
#endif
Scanner.cpp
#include "Scanner.h"
Scanner::Scanner(string exp): expressao(exp), posicao(0){}
Token Scanner::getToken()
{
std::stringstream valorToken;
string target;
while(expressao[posicao] == ' '){
posicao++;
}
if(isdigit(expressao[posicao])){
valorToken << expressao[posicao];
posicao++;
while(posicao < expressao.length() && isdigit(expressao[posicao])){
valorToken << expressao[posicao];
posicao++;
}
return new Token(numero, valorToken.str());
}
else if (this->expressao[posicao] == '+')
{
valorToken << "+";
valorToken >> target;
return new Token(soma, target);
posicao++;
}
else if (this->expressao[posicao] == '-')
{
return new Token(sub, "-");
posicao++;
}
else if (this->expressao[posicao] == '*')
{
return new Token(mult, "*");
posicao++;
}
else if (this->expressao[posicao] == '/')
{
return new Token(divisao, "/");
posicao++;
}
else
{
return new Token(erro, this->expressao[posicao]+"");
posicao++;
}
}
Token.h
#ifndef TOKEN_H
#define TOKEN_H
#include <string>
#include <iostream>
using namespace std;
enum TipoToken {
soma,
erro,
numero,
sub,
mult,
divisao
};
class Token
{
private:
string valor;
TipoToken tipo;
public:
Token(TipoToken tipo, string valor);
string print();
};
#endif
Token.cpp
#include "Token.h"
Token::Token(TipoToken tipo, string valor)
{
this->tipo = tipo;
this->valor = valor;
}
string Token::print()
{
if (this->tipo == soma)
{
return "Soma: " + this->valor;
}
else if (this->tipo == numero)
{
return "Numero: " + this->valor;
}
else if (this->tipo == sub)
{
return "Sub: " + this->valor;
}
else if (this->tipo == mult)
{
return "Mult: " + this->valor;
}
else if (this->tipo == divisao)
{
return "Div: " + this->valor;
}
else
{
return "Token invalido: " + this->valor;
}
}