This is for a school project where I am supposed to create a calculator that will graph functions. The graphing works, however my function that actually turns functions (the math kind) into data is not working for two major test case types, and I have no clue how to fix this. The test cases are input = -x^2 and input = x^2+2x+1, both of which when think through what I have written should work. I have been stumped by this for a while now, and I have not found a solution that does not mess up other equations.
double Solver(string input, double xValue)
{
int pos1;
int pos2;
int symbolpos;
string substring;
double value1;
double value2;
int count;
while (input.find_first_of(" ") != string::npos)
{
input.erase(input.find_first_of(" "), 1);
}
while (input.find("(") != string::npos && input.find(")") != string::npos)
{
pos1 = input.find_first_of("(");
if (pos1 > 0 && input[pos1 - 1] != '-')
{
input.insert(pos1, "*");
pos1++;
}
if (pos1 == 2 && input[0] == '-')
{
input.insert(pos1 - 1, "1");
pos1++;
}
pos2 = pos1;
count = 1;
while (count != 0)
{
pos2++;
if (input[pos2] == '(')
count++;
if (input[pos2] == ')')
count--;
}
substring = to_string(Solver(input.substr(pos1 + 1, pos2 - pos1 - 1), xValue));
input.replace(pos1, pos2 - pos1 + 1, substring);
}
while (input.find("x") != string::npos)
{
pos1 = input.find_first_of("x");
if (pos1 > 0)
{
input.insert(pos1, "*");
pos1++;
}
if (pos1 == 2 && input[0] == '-')
{
input.insert(pos1 - 1, "1");
pos1++;
}
input.replace(pos1, 1, to_string(xValue));
}
while (input.find("--") != string::npos)
{
input.replace(input.find("--"), 2, "+");
}
input = parsing(input, '^');
input = parsing(input, '*');
input = parsing(input, '/');
input = parsing(input, '+');
input = parsing(input, '-');
return stod(input);
}
string parsing(string tInput, char searchChar)
{
string input = tInput;
int pos1, pos2, symbolpos;
double value1, value2;
string substring;
while (input.substr(1).find_first_of(searchChar) != string::npos)
{
symbolpos = input.find_last_of(searchChar);
pos1 = 0;
for (int a = 0; a < symbolpos - 1; a++)
{
if (input[a] == '^')
pos1 = a++;
if (input[a] == '*')
pos1 = a++;
if (input[a] == '/')
pos1 = a++;
if (input[a] == '+')
pos1 = a++;
if (input[a] == '-')
pos1 = a;
}
pos2 = input.size();
for (int a = input.size(); a > symbolpos + 1; a--)
{
if (input[a] == '^')
pos2 = a--;
if (input[a] == '*')
pos2 = a--;
if (input[a] == '/')
pos2 = a--;
if (input[a] == '+')
pos2 = a--;
if (input[a] == '-')
pos2 = a--;
}
value1 = stod(input.substr(pos1, symbolpos - pos1));
value2 = stod(input.substr(symbolpos + 1, pos2 - symbolpos));
if (searchChar == '^')
substring = to_string(pow(value1, value2));
if (searchChar == '*')
substring = to_string(value1 * value2);
if (searchChar == '/')
substring = to_string(value1 / value2);
if (searchChar == '+')
substring = to_string(value1 + value2);
if (searchChar == '-')
substring = to_string(value1 - value2);
input.replace(pos1, pos2 - pos1, substring);
}
return input;
}
Thanks for your help!