473,396 Members | 1,797 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Code modification.

7
I wrote below code to do calculation. But it donesn't work for negative numbers like if input 4 + ( - 5 ), the program will crash. Any one can help me to modify the code to make it can calculate negative int also. Like if input 4 + ( - 5 ) should get -1, if input - 5 + 4 should get -1, ect..

Code:

#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int checkPrecedence(char c)

// return the precedence of the operator, a larger value means a higher precedence
{
if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
}
int main(void)
{
string input; // Enter expression here
getline(cin,input);
string::const_iterator iterInput;

// Converting Infix to Postfix

string output;
stack<char> stk;
for (iterInput=input.begin(); iterInput!=input.end(); iterInput++)
{
if ((*iterInput >= '0' && *iterInput <= '9') || (*iterInput == ' '))
{
if (!(output.empty() && *iterInput == ' ')) // ignore first ' ' in string
output.push_back(*iterInput); // add operand to postfix string
}
else if (*iterInput == '(')
{
stk.push(*iterInput); // add '(' to stack
iterInput++; // skip the next ' '
}
else if (*iterInput == ')')
{
while(stk.top() != '(') // remove all operator until '('
{
output.push_back(stk.top()); // add operator to postfix string
stk.pop(); // remove operator from stack
output.push_back(' '); // add ' ' to postfix string
}
stk.pop(); // remove the '('
iterInput++; // skip the next ' '
}
else // handle the operator
{
while (!stk.empty() && stk.top() != '(' && checkPrecedence(stk.top()) >= checkPrecedence(*iterInput))
{
output.push_back (stk.top()); // add operator to postfix string
stk.pop(); // remove operator from stack
}
stk.push(*iterInput); // add operator to stack
iterInput++; // skip the next ' '
}
}
while (!stk.empty()) // add all remaining operator from stack to postfix string
{
output.push_back(' '); // add ' ' to postfix string
output.push_back(stk.top()); // add operator to postfix string
stk.pop(); // remove operator from stack
}

cout << "Postfix expression: " << output << std::endl;

// Evaluate Postfix expression
stack<int> intStack;
string::const_iterator iterOutput;
string numString;
for (iterOutput= output.begin(); iterOutput!=output.end(); iterOutput++)
{
if (*iterOutput >= '0' && *iterOutput <= '9')
numString.push_back(*iterOutput);
else if (*iterOutput == ' ')
{
intStack.push(atoi(numString.c_str ()));
numString.clear();
}
else // operator
{
int rightOperand = intStack.top();
intStack.pop();
int leftOperand = intStack.top();
intStack.pop();

int result;
if (*iterOutput == '*')
result = leftOperand * rightOperand;
else if (*iterOutput == '/')
result = leftOperand / rightOperand;
else if (*iterOutput == '+')
result = leftOperand + rightOperand;
else if (*iterOutput == '-')
result = leftOperand - rightOperand;

intStack.push(result);
iterOutput++; // skip the next ' '
if (iterOutput== output.end()) // handle end of string condition
break;
}
}
cout << "Result: " << intStack.top() << endl;
system("pause");
}
Sep 21 '06 #1
1 2200
D_C
293 100+
Are you using the same character for negative numbers as minus signs? For example, -5 = 0-5. That's where you are confusing it, I bet. Each time you run into '-' check to see if the last thing pushed was a number. Otherwise, push 0, then '-'. Well I'm not sure if it's infix or postfix, therefore which order to push 0 and '-'. But you get the idea, right?

See where that gets you.
Sep 21 '06 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: nathan_kent_bullock | last post by:
Assume I am using a class Foo. I want to find out the modification time of the file that that class was defined in. How would I go about this? If I could find out the name of the file that Foo...
2
by: janek | last post by:
My question How can I do something like this... in Builder: In ListBox I've got a list of the files (load by the FindDir) and what should I do to pull out from these files the size and the time...
3
by: stan | last post by:
I am working on some documentation in html format and I would really like to display the date the html file, itself was modified. I am writing my documentation in vi and the html server involved is...
10
by: malv | last post by:
I am involved in a major scientific algorithm design problem in which simulation of the underlying physics and visualization play an important role. Algorithm adaptation from run to run often...
0
by: Marco Segurini | last post by:
HI, my form contains a combobox and a propertygrid control. At each string of the combobox is associated an object. When I select a string of the combobox the associated object is selected in...
1
by: Henry Law | last post by:
(I posted this to comp.infosystems.www.browsers.misc but there seems to be very little traffic there. I can't see another suitable group; is it on topic here? If not, any suggestions as to...
2
by: sgMuser | last post by:
Hi, I am not a good developer of Javascript codes. Needs this help to make some modification to this famous free javascript from Anarchos. i am using this in one of my webpage. What it does is,...
4
by: IdleBrain | last post by:
Hello All, Is it possible to obtain the last Modified date for the source code from within the application? If yes, please let me know how it is done.
13
by: ts-dev | last post by:
Is it possible to prevent modification of a python file once its been deployed? File permissions of the OS could be used..but that doesn't seem very secure. The root of my question is verifying...
2
by: Unpopular | last post by:
void directory::modification()//??????????? { clrscr(); cout<< "\n\t @@@@@@ @@@@@ @@@@@ @@@@@@ @@@@@ @ @ @@@@@@ "; cout<< "\n\t=====@ @ @ @ @ @ @@...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.