I have calculator code where I need to save a given line (one line at a time calculator) based on a certain character like ‘M’ being present at the end of the string. Also if ‘M’ is anywhere in the string then add the last saved string in place of that ‘M’.
I thought this could be easily done by (pseudo code),
foreach input element
if input element == 'M' && is last element
save = true
erase M element
if input element == 'M' && save != true
insert saved string into input
erase 'M' from input
if save == true
Set save string = input;
I attempt to do this in the method below but it is not working. I am not sure where or how to save the string so that it doesn’t get reset on every line. I get “string subscript out of range” (in another class, but due to this change) when I try to use an ‘M’ at the end of input.
const string operators = "*/+-";
const string memorize = "M";
list<string> lex(string input)
{
list<string> tokens;
bool save = true;
string saveInfo = "2";
string token;
for (unsigned int i = 0; i < input.length(); i++)
{
// Check if we need to save string element to memory
if ((memorize.find(input[i]) != string::npos) && (i == input.length() - 1))
{
save = true;
// Remove 'M' from end of string
input.erase(i);
}
// Check if 'M' is element
if (memorize.find(input[i]) != string::npos && !save)
{
// Insert saved string
input.insert(i, saveInfo);
// Remove M from string
input.erase(i);
}
// Save input
if (save)
{
saveInfo = input;
}
if (operators.find(input[i]) != string::npos)
{
// Add any token we've created so far
if (token.length())
{
tokens.push_back(token);
token.clear();
}
// Add this operator as a separate token
token.push_back(input[i]);
tokens.push_back(token);
token.clear();
}
else
{
// Grow the current token
token.push_back(input[i]);
}
}
// Any stragglers?
if (token.length())
{
tokens.push_back(token);
}
// Clean 'em up
for (list<string>::iterator i = tokens.begin(); i != tokens.end(); ++i)
{
*i = clean(*i);
}
return tokens;
}
saveInfo is currently just being set to “2” every time until I figure out where my string variable should be to keep the saved string instance each time.
Is this the right way to go about this problem? Is there a better way? Do you know why this isn’t working?
EDIT:
example input:
INPUT: 2+1M
OUTPUT: 3 **2+1 is saved
INPUT: M+5 **2+1 is inserted into this input string at 'M'
OUTPUT: 8
I have not worked with C++ in a long time, any help is appreciated!
First thing that comes to mind is this: you’re iterating over a sequence while you modify it by adding and removing items. that’s bound to cause tears since your indices are wrong after your insertion/deletion.