Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You are to code the function \'evaluate\' which evaluates an expression or indic

ID: 3625811 • Letter: Y

Question

You are to code the function 'evaluate' which evaluates an expression
or indicates that the expression was invalid. The expression is allowed
to be composed of integers as well as the operators: +, -, *, /. Note
that because of precedence, the '*' and '/' operators have to be
evaluated first so: "1 + 2 * 3" would evaluate to: 7, not 9.

The output from calling your 'evaluate' function using the strings
in 'list' should look something like:

No expression supplied: [ ]
Number expected, position: [1], in: [+]
Invalid symbol: [@], found in: [@], position: [1]
Number not expected, position: [3], in: [2 1+2]
3 - 7 + 8*9 => 68
1+2+2+3+3+3+4+4+4+4 => 30
1+2*3 => 7
10 / 4 + 2 => 4
Division by zero: [1 + 3 / 0]

this is the program:


#include <iostream>
#include <sstream>
#include <cstdlib>
#include <string>
#include <vector>
#include <cctype>

using std::ostringstream;
using std::string;
using std::vector;
using std::cout;
using std::endl;

static bool evaluate(const string &s, int *resultPtr, string &errMsg)
{
/* ==================================== */
/* === YOUR CODE GOES HERE ========== */
/* ==================================== */

return(false);
}

int main()
{
string list[] =
{
" ",
"+",
"@",
"2 1+2",
" 3 - 7 + 8*9",
"1+2+2+3+3+3+4+4+4+4",
"1+2*3",
"10 / 4 + 2",
"1 + 3 / 0"
};

string errMsg;
int result = 0;

for(int i = 0, n = sizeof(list) / sizeof(list[0]); i < n; i ++)
{
if(!evaluate(list[i], &result, errMsg))
cout << errMsg << endl;
else
cout << list[i] << " => " << result << endl;
}

return(0);
}

Explanation / Answer

string add = "+"; string str ("1+2"); string::iterator itr; int op1 = -1, op2 = -1; for(itr = str.begin(); itr Go left till you hit emptiness or another operator. -> Go right in the same way. -> Operate the numbers. -> Make new string, destroy old one, re-eval till complete.
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote