I am learning data structures and as I go through I needed to make a postfix input calculator in c.I wanted to make it using stack and stack of array.I wrote some code but it is not giving output instead it gives the first word i input in it.If I dont take input and give value in declaration of string this works but if I ask for input then it doesnt work.And i also tried to print strlength after the scanf it even if my input is 17 length it only prints 1.scan f is not working correctly or strlen is not working correctly.My code is :-
#include <stdio.h>
#include <string.h>
#include "stack_forpostfix.h"
int postfix(char *exp);
int isoperator1(char b);
int isnumericdigit1(char c);
int doevaluation(int oper1,char optr,int oper2);
int main(){
char *exp1;
int a;
printf("Enter the postfix expresssion\n");/*if we dont ask and put input in declaration the code works perfect,because if we ask the strlen is not working*/
scanf("%s",exp1); //2 3 * 5 4 * + 9 -
printf(" , %d , ",strlen(exp1));
a=postfix(exp1);
printf("%d\n",a);
}
int postfix(char *exp){
for(int i=0;i<strlen(exp);i++){
if(exp[i]==' ' || exp[i]==','){
continue;
}
else if(isoperator1(exp[i])){
int op2=gettop();
pop();
int op1=gettop();
pop();
int result=doevaluation(op1,exp[i],op2);
push(result);
}
else if(isnumericdigit1(exp[i])){
int oper=0;
while(i<strlen(exp) && isnumericdigit1(exp[i])){
oper=(oper*10)+(exp[i]-'0');
i++;
} //since i++ is there if no i-- exp[i] will escape one further
i--;
push(oper);
}
}
return gettop();
}
int isnumericdigit1(char c){
if (c>='0' && c<='9'){
return 1;
}
else return 0;
}
int isoperator1(char b){
if(b=='+'||b=='-'||b=='*'||b=='/'){
return 1;
}
else {
return 0;
}
}
int doevaluation(int oper1,char optr,int oper2){
if(optr=='+'){
return oper1+oper2;
}else if (optr=='-'){
return oper1-oper2;
}else if (optr=='*'){
return oper1*oper2;
}else if (optr=='/'){
return oper1/oper2;
}else {
printf("not valid");
return -1;
}
}
And my header file(stack_forpostfix.h) code is :-
#ifndef stackyfix
#define stackyfix
#define maxsize 111
int a[maxsize];
int top=-1;
void push(int r){
top++;
a[top]=r;
}
void pop(){
top--;
}
int gettop(){
return a[top];
}
#endif
In infix to postfix function, in place of str[i]=gettop(); there should be str[j]=gettop() so the expression entered inside the brackets can be pprocessed. Also add this piece of code after fgets to remove the '\n' that fgets may append.
fgets(b,sizeof(b),stdin);
for(int i=0;b[i]!='\0';i++){ // removes \n added by fgets
if(b[i]=='\0'){
if(b[i-1]=='\n'){
b[i-1]='\0';
}
}
}