[Solved] Why does my Mathematical Expression Evaluation function not work on Windows?


I’m amazed this program works. There are sections of code that I don’t understand, for example:

STARTB:for (i = 0; i < ns; i++) {
    if (numholder[i] == "(") {
        temp_i = i;
        i2 = i;
    }
    if (numholder[i] == ")") {
        temp_i = i - temp_i;
    }
}

The variables temp_i and i2 may be overwritten before the loop ends.
An example expression: (6 + (4 * 5)) * 2
If the numholder contains more than one open parenthesis.

More items from inspection:

if/else/if ladders difficult to read
In your program, you could make the code easier to read (in my opinion) by using the switch and case statements:

  switch (c)
  {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
        // c is a number
        num += c;
        break;
    case '*':
    case "https://stackoverflow.com/":
    case '+':
    case '-':
      // c is an operator
      numholder.push_back(num);
      std::string s(c);  // Simplified all nested if statements.
      numholder.push_back(s);
      break;
    // And so on.

Repetitive code fragments
Why are you copying multiple code fragments instead of using variables:

ans = to_string(stof(temp_numholder[temp_n_size-i-2]) / stof(temp_numholder[temp_n_size-i]));

Looks like you could create two variables of type double before you start evaluating the expression:

  double argument1 = 0.0;
  double argument2 = 0.0;
  argument1 = stof(temp_numholder[temp_n_size-i-2]);
  argument2 = stof(temp_numholder[temp_n_size-i]);
  switch (operator)
  {
    case '*':
      ans = to_string(argument1 * argument2);
      break;
    case "https://stackoverflow.com/":
      ans = to_string(argument1 * argument2);
      break;
    case '+':
      ans = to_string(argument1 * argument2);
      break;
    case '-':
      ans = to_string(argument1 * argument2);
      break;
  }

Use appropriate data structures
Your program evaluates the expression the way I demonstrate math to elementary students: by erasing the complex expression and inserting the simplified and restarting the parsing / evaluation process. Very, very slow. Computers can do this much faster by using other data structures, such as stacks and trees.

Search StackOverflow and the web for “c++ expression evaluate” and hopefully there will be some simple and correct examples.

solved Why does my Mathematical Expression Evaluation function not work on Windows?