Apr 6, 2018 at 7:00am UTC
#include <sstream>
#include <iostream>
using namespace std;
using namespace std;
//const char * expressionToParse = "6.5-2.5*10/5+2*5";
const char * expressionToParse = "-5+2";
istringstream parse(expressionToParse) ;
char peek()
{
return static_cast<char>(parse.peek()) ;
}
char get()
{
return static_cast<char>(parse.get()) ;
}
double expression();
double number()
{
double result ;
parse >> result ;
return result;
}
double factor()
{
if ((peek() >= '0' && peek() <= '9') || peek() == '.')
return number();
else if (peek() == '(')
{
get(); // '('
double result = expression();
get(); // ')'
return result;
}
else if (peek() == '-')
{
get();
return -expression();
}
return 0; // error
}
double term()
{
double result = factor();
while (peek() == '*' || peek() == '/')
if (get() == '*')
result *= factor();
else
result /= factor();
return result;
}
double expression()
{
double result = term();
while (peek() == '+' || peek() == '-')
if (get() == '+')
result += term();
else
result -= term();
return result;
}
int main(double argc, char* argv[])
{
double result = expression();
cout << result << endl;
return 0;
}
// This is working fine for all inputs but when we enter input as -3+2 answer is -5 can someone help
Apr 6, 2018 at 12:43pm UTC
Hi @coder777 and dhayden.... if you could give the code snippet as in where and what to change . I need it as an urgent code assigment. Please help
Apr 6, 2018 at 8:00pm UTC
We have given enough information for you to figure it out. Sorry, but the goal of this website is to help you become a better programmer, not to do your work for you.