In: Computer Science
can someone translate this pseudo code to actual c++ code
while (not the end of the input)
If the next input is a number read it and push it on the stack
else If the next input is an operator, read it
pop 2 operands off of the stack
apply the operator
push the result onto the stack
When you reach the end of the input:
if there is one number on the stack, print it else error
// Here is your pseudo code in c++ as per all instruction
#include <iostream>
#include <stack>
using namespace std;
int stack_solver(string str) // Here is function to solve input string
{
int i=0,length,a,b;
stack<int> s; // Here we make instance s of stack predefined class in C++ library
length=str.length(); // Here we input the length of strung via length()
while(i<length) // This will run upto end of the string
{
if(str[i]>='0'&&str[i]<='9') // Here we check for operand
s.push(str[i]-'0'); // if oprand push in stack
else if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')) // Here we check for any input other than operator and operand
return -1;
else // here else for operator
{
a= s.top(); //here we store the top most element in a
s.pop(); // Here we pop the topmost element
b= s.top(); // here we store the next top most element in b
s.pop(); //Here we pop the next topmost element
if(str[i]=='-') // Here we check for operation to do on operand and push the result on stack
s.push(b-a);
else if(str[i]=='+') // Here we check for operation to do on operand and push the result on stack
s.push(b+a);
else if (str[i]=='/') // Here we check for operation to do on operand and push the result on stack
s.push(b/a);
else if(str[i]=='*') // Here we check for operation to do on operand and push the result on stack
s.push(b*a);
}
i++;
}
if(s.size()==1) // here we check for only one element in stack if true then return
return s.top();
else
return -1; // else return -1 to print the ERROR
}
int main()
{
string str; // Here we declare the string str
cout<<"Enter the string of operator and operands "; // Here we alert the user for input the string
getline(cin,str); // Here we input the string
if(stack_solver(str)==-1) // Here we check for any invalid input
cout<<"ERROR";
else
cout<<stack_solver(str); // Here we print our result if input is correct
return 0;
}
Output for correct input:
Output for stack has left with more than one number
Output for incorrect input:
Please hit the like button if you find this helpful for you THANK YOU AND HAPPY LEARNING:)