Prefix to Post fix using C - c

The question is:
WAP to convert a given Prefix expression into its equivalent Postfix
expression and evaluate it using stack.
I have written this code, it takes the input but doesn't display the output.
//header files
#include<stdio.h>
#include<string.h>
//global variables
char stack[50];
int top = -1;
void push(char s)
{
stack[++top]=s;
}
//function to pop an element
char pop()
{
return stack[top--];
}
// funtion to check if the character is operator or not
int is_operator(char x)
{
switch (x)
{
case '+':
case '-':
case '/':
case '*':
return 1;
}
return 0;
}
//function to Convert prefix to Postfix
void convert()
{
int i,l;
char op1,op2,tmp;
char exp[50];
printf("Enter the prefix expression: ");
gets(exp);
//length of expression
l = strlen(exp);
//scanning from right to left
for(i = l - 1; i >= 0; i--)
{
//checking if the symbol is an operator
if (is_operator(exp[i]))
{
//popping two operands from stack
op1 = stack[top];
pop();
op2 = stack[top];
pop();
//concating the operands and operator
tmp = op1 + op2 + exp[i];
//Pushing the temporary string to stack
push(tmp);
}
//if it is an operand
else
{
//push the operand to the stack
push((exp[i]));
}
}
//printf("The postfix expression is: %s",stack[top].c_str());
printf("%s ",stack[top]);
}
//main function
int main()
{
convert();
return 0;
}
when i run the code it takes the prefix expression but immediately after that it crashes and returns to the terminal?
Can anyone please help me with the code i am having difficulty in understanding what mistake i have made.
Also if possible give a little explanation what mistake i did in the code.

In this algorithm, a stack of strings is required. But you are using an array of char.
The exp[i] returns a char. So just can not expect tmp = op1 + op2 + exp[i] to concat them into a string in c.
In c strcpy() can be used to copy a string and strcat() can be used to concat strings.
There are several ways to convert a char to a string of one char tailing NULL. In this code (char[2]){(char)exp[i], '\0'} is used to get a string containing exp[i] and NULL char.
In the solution code there is a memory limitation. The input expression should be in 50 chars (including '\0') .
Solution code :
#include<stdio.h>
#include<string.h>
char stack[50][50];
int top = -1;
void clear_stack() {
top = -1 ;
}
void push(char *s)
{
strcpy(stack[++top], s) ;
}
char* pop()
{
return stack[top--];
}
int is_operator(char x)
{
if(x == '+' ||x == '-'||x == '*'||x == '/'){
return 1;
}
else{
return 0;
}
}
//function to Convert prefix to Postfix
void convert(char *exp)
{
clear_stack() ;
int i,l;
char op1[50],op2[50];
l = strlen(exp);
//scanning from right to left
for(i = l - 1; i >= 0; i--)
{
//checking if the symbol is an operator
if (is_operator(exp[i]))
{
//popping two operands from stack
strcpy(op1, pop()) ;
strcpy(op2, pop()) ;;
//concating the operands and operator
strcat(op1 , strcat(op2 , (char[2]) {(char)exp[i], '\0'})) ;
//Pushing the temporary string to stack
push(op1);
}
//if it is an operand
else
{
//push the operand to the stack
push((char[2]){(char)exp[i], '\0'});
}
}
//printf("The postfix expression is: %s",stack[top].c_str());
printf("%s\n",stack[top]);
}
//main function
int main()
{
convert("*-A/BC-/AKL");
convert("+ab");
convert("*+abc");
convert("*a+bc");
convert("+/ab/cd");
convert("*+ab+cd");
convert("-*+abcd");
return 0;
}
Output :
ABC/-AK/L-*
ab+
ab+c*
abc+*
ab/cd/+
ab+cd+*
ab+c*d-

Related

Expression Tree - Operations with Characters

The user enters a string with an operation such as 4*5+2/3 and the code is supposed to make an expression tree out of it and the calculate said expression tree. I am having a problem where the program is making the expression tree with the decimal values of the ascii table instead of the actual numbers.
For example instead of 4*5+2/3, the program is storing and using 52 42 53 43 50 47 51 for the calculations. My desired run screen would be:
1 //this is the number of strings
4*5+2/3 //this is the string itself
20 //this is the result
However what I am getting is:
1 //this is the number of strings
4*5+2/3 //this is the string itself
2756 //this is the result
That is because the code is doing 52*53+50/51(because it is using the ascii values) and not 4*5+2/3.
I believe the reason for this is because I am storing 4*5+2/3 in a string of char and not in an array of int. I do not know if this is the case and would like some help.
You will not be able to run the following code as it is not complete but the whole program is five files and I do not know if I should put all of it here. I am new to both trees and StackOverflow.
This is my Make Expression Tree function and my Calculate Expression Tree function:
BTreeNode* MakeExpTree(char* exp, int len)
{
Stack stack;
BTreeNode * node, *right_node, *left_node;
InitStack(&stack);
for(int i = 0; i < len; i++){
if('0' <= exp[i] && exp[i] <= '9'){
node = CreateNode(exp[i]);
}
else{
right_node = PeekNode(&stack), Pop(&stack);
left_node = PeekNode(&stack), Pop(&stack);
node = CreateNode(exp[i]);
CreateRightSubtree(node, right_node);
CreateLeftSubtree(node, left_node);
}
PushNode(&stack, node);
}
return PeekNode(&stack);
}
int CalculateExpTree(BTreeNode* root)
{
int ret, op1, op2;
if(root == NULL){
return 0;
}
if(root->left_child == NULL && root->right_child == NULL){
return root->item;
}
op1 = CalculateExpTree(root->left_child);
op2 = CalculateExpTree(root->right_child);
switch(root->item){
case '+':
ret = op1 + op2;
break;
case '-':
ret = op1 - op2;
break;
case '*':
ret = op1 * op2;
break;
case '/':
ret = op1 / op2;
break;
case '#':
ret = op1 * pow( 2, op2);
break;
case '#':
ret = op1 / pow( 2, op2);
break;
}
return ret;
}
This is how I store the string from stdin in main function:
int main()
{
int num_exp, result, len = 0;
char input[10];
char IDK[129];
fgets(input, 9, stdin); //user enters number of strings
int m = sscanf(input, "%d", &num_exp);
char string[100][129] = { 0 };
char postfix[100][129] = { 0 };
for(int i = 0; i < num_exp; i++){
fgets(IDK, 129, stdin); //user enters string
int mm = sscanf(IDK, "%s", string[i]); //is this where the problem lies?
} //should I not be storing it in a char string?
for(int x = 0; x < num_exp; x++){
InfixToPostfix(string[x], postfix[x]); //converts strings from infix to postfix
}
BTreeNode* tree;
for(int k = 0; k < 129; k++){ //calculates length of string
if(postfix[0][k] == '\0'){
break;
}
len++;
}
tree = MakeExpTree(postfix[0], len); //makes expression tree
result = CalculateExpTree(tree); //calculates expression tree
//or is the problem in this function?
printf("%d \n", result);
return 0;
}
I am not understanding clearly what you are doing and it would help my learning too if you shared from what source are you learning these (we can chat in chat room) but I also tried to do similar thing and in my style it works partially (that is, sometimes when I insert larger number the answer is wrong but for small numbers generally correct).So you might get some help form my style of this code that calculates given string (A little help for me also would be appreciated commenters!!). My code:
#include <stdio.h>
#include <string.h>
#include "stackforcalc.h"
int isOperand(char b){
if(b>='0' && b<='9'){
return 1;
}else{
return 0;
}
}
int isOperator(char b){
if(b=='+' || b=='-' || b=='*' || b=='/'){
return 1;
}
return 0;
}
int getwt(char b){
int g=-1;
switch (b)
{
case '+':
case '-':
g=1;
break;
case '/':
case '*':
g=28787868;
break;
}
return g;
}
int higherprecedence(char a,char b){
int c=getwt(a);
int d=getwt(b);
return (c>=d)?1:0;
}
int infToPost(char *b,char *str){
int j=0;
for(int i=0;i<strlen(b);i++){
if(b[i]== ' ' || b[i]== ',' ){
continue;
}
else if(isOperator(b[i])){
str[j]=' ';
j++;
while(!empty() && gettop() != '(' && higherprecedence(gettop(),b[i])){
str[j]=gettop();
j++;
pop();
}
push(b[i]);
}
else if(isOperand(b[i])){
str[j]=b[i];
j++;
}
else if(b[i]=='('){
push(b[i]);
}
else if(b[i] ==')'){
while(!empty() && gettop() != '('){
str[i]=gettop();
j++;
pop();
}
pop();
}
}
while(!empty()){
str[j]=gettop();
j++;
pop();
}
}
int Evaluate(int t,char y,int r){
int ty;
switch(y){
case '+':
ty=t+r;
break;
case '-':
ty=r-t; //I inverted these.
break;
case '*':
ty=r*t;
break;
case '/': //I inverted these because
ty=r/t; //even though I did t/r it performed r/t.
break; //may be somewhere before the numbers were swapped
default:
ty=-1;
break;
}
return ty;
}
int calculatepostfix(char *c){
for(int i=0;i<strlen(c);i++){
if(c[i]==' ' || c[i]==','){
continue;
}
else if(isOperator(c[i])){
int op1=gettop2();
pop2();
int op2=gettop2();
pop2();
int oper=Evaluate(op1,c[i],op2);
push2(oper);
}
else if(isOperand(c[i])){
int res=0;
while(i<strlen(c) && isOperand(c[i])){
res=(res*10)+(c[i]-'0');
i++;
}
i--;
push2(res);
}
}
return gettop2();
}
int main(){
char b[65];
printf("\n \n**-- Calculator --**\n");
printf("Enter expression: ");
fgets(b,sizeof(b),stdin);
char str[50];
infToPost(b,str);
int tt =calculatepostfix(str);
printf("Your answer is: %d",tt);
}
The code in "stackforcalc.h" is
#ifndef stacycalc
#define stacycalc
#define maxsize 50
char a[maxsize];
int top=-1;
int abc[maxsize];
int to=-1;
void push2(int re){ abc[++to]=re; }
void push(char b){ a[++top]=b; }
void pop2(){ to--; }
void pop(){ top--;}
int gettop2(){ return (to==-1)?-1:abc[to]; }
char gettop(){ return (top==-1)?0:a[top]; }
int empty(){ return (top==-1)?1:0; }
#endif
That is because the code is doing 52*53+50/51 (because it is using the ascii values) and not 4*5+2/3.
Yes.
I believe the reason for this is because I am storing 4*5+2/3 in a string of char and not in an array of int.
No.
In C, int is just a bigger char. There's nothing magical about them; they both hold numbers.
There are a variety of ways to derive the integer value from an ASCII character. If you have exactly one character and don't want to use a library, you can "mask off" the bits: since the ASCII range for digits is 0x30 - 0x39,
static char string[] = "4";
int value = string[0] & 0x0F;
does the trick. For more complex operations, my favorite is sscanf(3), but many use atoi(3) or various flavors of strtol(3).

infix to postfix converstion in C with multiple digits input

What I'm trying to obtain is a calculator that will take infix notation, ignore insignificant whitespace characters like " " or '#', then convert that infix notaion into postfix notation and do simple calculations like addition, subtraction etc. So far the code is taking input in infix notation trimming it in a way that ignores insignificant whitespace characters and outputs the postfix notation.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>;
#include <ctype.h>;
#define MAX_LENGTH 100
//Functions
void push(char x);
char pop();
void trimString(char string[], char newString[]);
void inputToRPN(char trimmedExp[], char rpnExp[]);
int calculateRPN(char rpnExp[]);
char stack[MAX_LENGTH];
char resStack[MAX_LENGTH];
int top = -1;
int resTop = -1;
int index = 0;
int main() {
int res;
char exp[MAX_LENGTH] = "10 +2";
char trimmedExpression[MAX_LENGTH];
char rpnExpression[MAX_LENGTH];
// Input commented out as per suggestion in comments
//printf("Enter expression : ");
//fgets(exp, 100, stdin);
printf("Infix expression: %s \n", exp);
trimString(exp, trimmedExpression);
printf("\n");
inputToRPN(trimmedExpression, rpnExpression);
res = calculateRPN(rpnExpression);
//printf("Result of calculation: %d", res);
return 0;
}
void push(char x) {
stack[++top] = x;
}
char pop() {
if (top == -1)
return -1;
else
return stack[top--];
}
int priority(char x) {
if (x == '(')
return 0;
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/')
return 2;
return 0;
}
void trimString(char string[], char newString[]) {
int i = 0, j = 0;
while (string[i] != '\0' && string[i] != 10) {
// Range of significant characters
if (string[i] >= '(' && string[i] <= '9') {
newString[j] = string[i];
i++, j++;
}
else {
i++;
}
}
newString[j] = 0;
}
void inputToRPN(char trimmedExp[], char rpnExp[]) {
char* e, x;
e = trimmedExp;
while (*e != '\0') {
// Add to RPN if character is alphanumeric
if (isalnum(*e)) {
rpnExp[index] = *e;
index++;
}
// Add to stack if is an open brace
else if (*e == '(')
push(*e);
// Add all operators to the expression until finding open braces
else if (*e == ')') {
while ((x = pop()) != '(') {
rpnExp[index] = x;
index++;
}
}
// If none of the above, that is an operator - check it's priority.
// If it's priority is less that that of the one on top of the stack add the operator from the top of the stack to the expression; untill it's priority is higher.
// At the end add current operator to the stack.
else {
while (priority(stack[top]) >= priority(*e)) {
rpnExp[index] = pop();
index++;
}
push(*e);
}
e++;
}
while (top != -1) {
rpnExp[index] = pop();
index++;
}
// Terminating character at the end of the string
rpnExp[index] = 0;
}
void pushRes(char x) {
printf("pushing: %c \n", x);
resStack[++resTop] = x;
}
char popRes() {
printf("poping \n");
if (resTop == -1)
return -1;
else
return resStack[resTop--];
}
int isValidOperator(char c) {
if (c == '/' || c == '*' || c == '+' || c == '-')
return 1;
else
return 0;
}
int calculateRPN(char rpnExp[]) {
// Doesnt do anything yet, just prints out the compiled reverse polish notation
char* c;
int result = 0;
c = rpnExp;
printf("Postfix expression: %s", rpnExp);
return result;
}
The problem I've stumbled upon is when the infix input has multiple digits say 10+2 the code will treat each digit individually. Therefore the whole expression will be invalid when calculating result. I'm almost certain the issue lies in this line of code:
// Add to RPN if character is alphanumeric
if (isalnum(*e)) {
rpnExp[index] = *e;
index++;
}
Despite that I've got no idea how should i treat multiple digits while adding them to the expression, since the input is in form of character and there can be N amount of digits that have coresponding ascii values which range from 0-9. Looking forward to your answears.
Edit: made it so the code compiles and the input is hard coded.
Okay, so thanks to Bodos suggestions I've fixed the issue. Adding one while loop in this section:
if (isalnum(*e)) {
rpnExp[index] = *e;
index++;
}
enabled me to add one character after every number (including the N digit ones).
Thanks to which I was later able to perform calculations in calculateRPN function that would eventually lead to correct answear.
The issue has been resolved.

How to convert a string with mathematical operators to number (integer or float)

I have a problem with converting a string like "(5+2)*3" to be able to evaluate to be 21.
Here is my code:
char inp[10];
printf("Write it: ");
scanf("%s", inp);
printf("Okay, computing!\n");
printf("INPUT: %s \n", inp);
printf("It's %d \n", (int)inp);
I would like to get a number at the end.
This code is working:
printf("19+31 is '''%d'''", 19+31);
And i need to use the second argument - the 19+31 - to be my input.
The first code outputs this:
Write it: 4+4
Okay, computing!
INPUT: 4+4
It's 329554704
You can't do this directly. C has no built-in way to evaluate expressions which are entered (as an arbitrary string) at run time. But that's exactly what you need here.
Writing an expression evaluator is a very interesting exercise -- but probably not for your first (or even second) C program.
Here is a tiny example to give you a feel for it:
#include <stdio.h>
#include <stdlib.h>
int eval(char *);
int main()
{
char expr[100];
int x;
printf("Type an expression:\n");
fgets(expr, sizeof(expr), stdin);
x = eval(expr);
printf("Answer: %d\n", x);
}
int eval(char *str)
{
char *p;
int lhs, rhs;
char op;
int r = 0;
lhs = strtol(str, &p, 10);
while(*p == ' ') p++;
op = *p++;
rhs = strtol(p, &p, 10);
switch(op) {
case '+': r = lhs + rhs; break;
case '-': r = lhs - rhs; break;
case '*': r = lhs * rhs; break;
case '/': r = lhs / rhs; break;
}
return r;
}
This works, but it's terribly limited: it handles only simple two-term expressions a+b, a-b, a*b, and a/b. (What's worse, there's no obvious way to extend it to handle fully-general expressions with parentheses and more than two terms. Handling fully-general expressions will require a completely different, more sophisticated approach.)
Addendum: Here's a -- didactically challenged -- example of that "more sophisticated approach":
#include <stdio.h>
#include <ctype.h>
int e0(char *);
int e1(char **);
int e2(char **);
int e3(char **);
void w(char **);
void q();
int main()
{
char b[100];
while(fgets(b, sizeof(b), stdin))
printf("%d\n",e0(b));
}
int e0(char *s)
{
return e1(&s);
}
int e1(char **s)
{
int r = e2(s);
while(1) {
w(s);
switch(*(*s)++) {
case '+': r += e2(s); break;
case '-': r -= e2(s); break;
default: (*s)--; return r;
}
}
}
int e2(char **s)
{
int r = e3(s);
while(1) {
w(s);
switch(*(*s)++) {
case '*': r *= e3(s); break;
case '/': r /= e3(s); break;
default: (*s)--; return r;
}
}
}
int e3(char **s)
{
int c;
w(s);
c = *(*s)++;
if(isdigit(c)) {
c -= '0';
while(isdigit(**s)) c = 10 *c + *(*s)++ - '0';
return c;
} else if(c == '-') {
return -e3(s);
} else if(c == '(') {
int r = e1(s);
w(s);
if(*(*s)++ != ')') {
q();
(*s)--;
}
return r;
} else {
q();
return 0;
}
}
void w(char **s)
{
while(**s == ' ' || **s == '\t' || **s == '\n') (*s)++;
}
void q()
{
fprintf(stderr, "?\n");
}
This works, and you're welcome to compile it and play with it. It's an unsophisticated implementation of a recursive descent parser for simple expressions involving integers, +, -, *, /, parentheses, and unary -. It can handle things like 1+2*3, (1+2)*3, and 1----2----3. (That last example is legal under this parser, though not in C.)
I called it "didactically challenged" because it's not designed for teaching -- it's a cleanup of an ill-inspired attempt I made many years ago to squeeze the code down to a bare minimum, resulting in something that was practically an IOCCC entry.

How do I evaluate decimals & floating point numbers in scientific e notation - e.g. {1.23e4}. in postfix?

I have written my code to evaluate from postfix to result. However, I am stuck at how to do it when the postfix is going to be in decimals & floating point numbers in scientific e notation - e.g. {1.23e4}. Any specific suggestion would be highly appreciated. Thanks.
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#define SIZE 50 /* Size of Stack */
double s[SIZE];
int top=-1; /* Global declarations */
int flag=0;
double pop()
{ /* Function for POP operation */
return(s[top--]);
}
double push(double elem)
{ /* Function for PUSH operation */
if(flag==1){
int num;
num=pop();
s[++top]=elem+10*num;
}
else if(flag==0){
s[++top]=elem;
flag=1;
}
}
void main()
{ /* Main Program */
char pofx[50],ch;
int i=0;
double op1,op2;
printf("Enter the Postfix Expression:");
fgets(pofx,100,stdin);
while( (ch=pofx[i++]) != '\n')
{
if(isdigit(ch)) push(ch-'0'); /* Push the operand */
else if(ch==' ')
flag=0;
else
{ /* Operator,pop two operands */
flag=0;
op2=pop();
op1=pop();
switch(ch)
{
case '+':push(op1+op2);break;
case '-':push(op1-op2);break;
case '*':push(op1*op2);break;
case '/':push(op1/op2);break;
case '^':push(pow(op1,op2));break;
default:
printf("Input invalid ... give proper input\n");
return 0;
}
}
}
printf("Result: %lf\n",s[top]);
}
How do I evaluate decimals & floating point numbers in scientific e notation ... (?)
To convert a string into FP value use strtod() #M Oehm
Yet code has other problems in that the operator symbols '-' and '+' may also begin valid value tokens like -123.45.
// insufficient test to determine if the next part of the string is a number or operator.
if(isdigit(ch))
push(ch-'0');
Use strtod() to convert text to double and determine if the next part of the string is a double.
Alternative code:
const char *st = pofx;
while (*st) {
char *end; //location to store end of FP parsing
double value = strtod(st, &end);
if (end > st) {
push(value);
st = end;
} else if (isspace((unsigned char) *st)) {
st++;
} else {
switch (*st) {
case '+':push(pop() + pop());break; // pop order irrelevant
case '-':{ double t = pop(); push(pop() - t);break; } // pop order relevant
case '*':push(pop() * pop());break;
...
default: {
printf("Input invalid operator: character code %d\n", *st);
return 0;
}
} // end switch
st++;
}
}
Re-write push()
void push(double elem) {
if (top + 1 >= SIZE) {
printf("Stack overflow\n");
return;
}
s[++top] = elem;
}
Wrong argument to fgets()
char pofx[50];
// fgets(pofx,100,stdin); // 100??
fgets(pofx, sizeof pofx, stdin); // better
The function strtod from <stdlib.h> will parse a double for you. It takes the string to parse and a pointer to a string, that will begin with the first unparsed character. (There's a similar function for long integers, strtol.)
Here's an example of how this might work in your case. (The code just prints out the tokens and doesn't do any calculations.)
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int is_number(const char *p)
{
if (*p == '-' || *p == '+') p++;
if (*p == '.') p++;
return isdigit((unsigned char) *p);
}
int main(void)
{
const char *line = " .1 20.1* 1.0e-3+2e+7 * -1.0*";
const char *p = line;
while (isspace((unsigned char) *p)) p++;
while (*p) {
if (is_number(p, after_op)) {
char *end;
double x = strtod(p, &end);
if (p == end) {
puts("Illegal number");
p++;
} else {
printf("Number %g\n", x);
p = end;
}
} else {
int c = *p++;
switch (c) {
case '+': puts("Operator add"); break;
case '-': puts("Operator sub"); break;
case '*': puts("Operator mult"); break;
case '/': puts("Operator div"); break;
case '^': puts("Operator pow"); break;
default: printf("Illegal char '%c'\n", c);
}
}
while (isspace((unsigned char) *p)) p++;
}
return 0;
}
This is still very crude, mind you. Strings like 20x21 will be parsed as number 20, unknown character x and number 21. While this code is bad at detecting and reporting errors (which really should be done, but it's left as an exercise, yadda, yadda), it works for valid input.
[Edit: I've incorporated chux's suggestions and also made the code compatible to read numbers with explicit signs, but that means that the binary operators - and + cannot immediately be followed by a digit. Pick your poison. I've also allowed the abridged version that leaves out a leading zero, e.g. .12, a format that I'm not very fond of.]

Program Crashes After String Input

My program basically converts an infix expression to a postfix expression, although so far my program only accepts single digits. Anyway when I try to compile, right after inputting my infix expression, the program crashes almost immediately. My code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int priority(char x); // Determines priority of incoming operator.
void push(char x); // Pushes element to stack.
char pop(); // Pops element from stack.
char stack[10];
int top = -1;
int main() {
char init[20];
printf("Enter an expression: ");
fgets(init, 20, stdin);
int x = 0, y, z = 0;
static char result[20];
while (init[x++] != '\0') {
if (isalnum(init[x]))
result[z++] = init[x]; // Operand printed out immediately.
else if (init[x] == '(')
push(init[x]); // '(' character pushed.
else if (init[x] == ')') {
while ((y = pop()) != '(')// Popping elements from stack until reaching '('
result[z++] = y;
} else if (init[x] == ' ') {
z++;
else {
while (priority(init[x]) <= priority(stack[top])) // If expression operator has higher precedence than stack operator, expression operator is pushed onto stack. Else stack operator is popped and printed out.
result[z++] = pop();
push(init[x]);
}
}
while (top != -1)
result[z++] = pop(); // Remaining operators printed out.
printf("Final expression is %s.\n", result);
}
int priority(char x) {
int precedence = 0;
if(x == '(')
precedence = 0;
if(x == '+' || x == '-')
precedence = 1;
if(x == '*' || x == '/')
precedence = 2;
if(x == '^')
precedence = 3;
return precedence;
}
void push(char x) {
stack[++top] = x;
}
char pop() {
return stack[top--];
}
I had a version of this that worked but when I look at this version, nothing seems to be any different. Can someone please tell me what I'm missing?
A major issue that I found is:
while (init[x++] != '\0')
While you increment the value of x in the condition check of loop, you again try to access it in call to function :
isalnum(init[x])
the first number is never evaluated this way. So if you enter "5+2", only "+2" will be evaluated, which is an invalid infix expression.

Resources