This is the member function that tokenizes the string and pu
This is the member function that tokenizes the string and puts the tokens in a vector.
void Expression::set(const string& s)
{
original = s;
//valid = false;**not needed for this assignment
//type = illegal;**not needed for this assignment
Token tok;
string temp;
for(unsigned int i = 0; i < s.size(); i++)
{
if ((s[i] == \'(\')||(s[i] == \')\')||(s[i] == \'+\')||(s[i] == \'-\')||(s[i] == \'*\')||(s[i] == \'/\')||(s[i] == \'%\')||(s[i] == \'=\')||(s[i] == \' \'))
{
if (temp.size() > 0)
{
tok.set(temp);
tokenized.push_back(tok);
temp.clear();
}
if (s[i] != \' \')
{
temp = s[i];
tok.set(temp);
tokenized.push_back(tok);
temp.clear();
}
}
else
{
string temp2;
temp2 = s[i];
temp.append(temp2);
}
if(s.size() == i+1)
{
tok.set(temp);
tokenized.push_back(tok);
}
}
}
This is the main file I\'m calling the test cases from:
string s1 =\"(2+3)*4\";
string s2 =\" dd - s3.dis _+23a9((\";
string s3 =\"a+b+C+(111-444)\";
string s4 =\"55555+3k444,%84\";
Expression e1(s1);
e1.display();
cout << endl;
Expression e2(s2);
e2.display();
cout << endl;
Expression e3(s3);
e3.display();
cout << endl;
Expression e4(s4);
e4.display();
return 0;
}
This is the output:
Number of tokens: 7
Tokens: (, 2, +, 3, ), *, 4,
Original expression: dd - s3.dis _+23a9((
Number of tokens: 9
Tokens: dd, -, s3.dis, _, +, 23a9, (, (, ,
Original expression: a+b+C+(111-444)
Number of tokens: 12
Tokens: a, +, b, +, C, +, (, 111, -, 444, ), ,
Original expression: 55555+3k444,%84
Number of tokens: 5
Tokens: 55555, +, 3k444,, %, 84,
Cases 1 and 4 work as expected, 2 and 3 add a space as a token to the end of the vector. Any thoughts?
Solution
See the problem occurs when the last element is a non-digit. You have placed an if condition at last to push temp but what if temp is already pushed and now temp is empty that is what\'s happening.
Suppose temp has 444 and s[i] is ) so inside first if condition you are pushing temp and clearing it and at the end also you are pushing temp which is empty now because of which space is coming.
Change your last condition to:
if(temp.size>0 && s.size() == i+1)

