here is a simple program for postfix calculator using stack, but the atoi() causes it to crash. Why is it happening? I have tried converting the char to string using ch-'0' and it works but the atoi() function for char to int conversion does not seem to work in this case.
Is it because ch is a char nor string eg. char ch; and not char ch[20];
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
int num[MAX],tos=-1;
push(int x)
{
if(tos==MAX)
{
printf("the stack is full");
}
else
{
printf(" l");
tos++;
num[tos]=x;
}
}
int pop()
{
if(tos<0)
{
printf("stack underflow");
}
else
return num[tos--];
}
int main()
{
char postfix[MAX],exp[MAX],ch,val;
int a,b;
printf("enter the postfix expression");
fgets(postfix,MAX,stdin);
strcpy(exp,postfix);
for(int i=0;i<strlen(postfix);i++)
{
printf(" xox ");
ch=postfix[i];
if(isdigit(ch))
{
push(ch - '0');
printf(" %d ",atoi(ch));
}
else
{
printf("%d",tos);
a=pop();
b=pop();
switch(ch)
{
case '+':
val=a+b;
break;
case '-':
val=a-b;
break;
case '*':
val=a*b;
break;
case '/':
val=a/b;
break;
}
printf("%d",val);
push(val);
}
}
printf("the result of the expression %s = %d",exp,num[0]);
return 0;
}
char. - Blazecharthat represents a number from 0 to 9 to the respective integer, simply subtract'0'like you're already doing in your code. If you want it to keep the same value (so for instance'0'is48in ASCII), just assign the char to the int variable. - Blazeatoi(ch)shouldn't even compile. Your compiler is either terribly bad or it is not configured correctly. - Lundindefault: printf("<%d>\n", ch);to see a problem. - chux - Reinstate Monicaatoi. Hint:atoiexpects a pointer to a string, but you're passing achar. You're mixung up strings and chars, read the chapter dealing with strings in your C text book. - Jabberwocky