Hello, my assignment is to write a postfix calculator. I have written the program. It works well, except for when the user enters in an error. Lets say, user enters "2 A +" it changes the A to a '0'. Which it shouldn't be doing. I have tried strtol() as well, but again, it does the same thing. Is there something else I can do to achieve the same results as atoi() but also not make an 'error' a 0?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Macro for the size of the stack
#define STACKSIZE 50
// Intiate top and the stack size
long int top = 0;
long int stack[STACKSIZE] = {0};
// Compare the entered string
int stringEqualTo(char *first, char *second)
{
return (strcmp(first, second) == 0);
}
// Pop function
int pop(void)
{
long int returnNum;
// Return value on the top of the stack.
returnNum = stack[top];
// Move the stack pointer down if not at the lowest point.
if (top > 0)
{
top--;
}
return returnNum;
}
// Push function
int push(int num)
{
stack[++top] = num;
return num;
}
int main()
{
char input[50];
long int numIn;
long int sum, originalPop, status;
do
{
// Read input
status = scanf("%s", input);
// Convert input to int
numIn = atoi(input);
if(status != EOF)
{
if(numIn == 0)
{
// Addition
if(stringEqualTo(input, "+"))
{
sum = push(pop() + pop());
}
// Subtraction
else if (stringEqualTo(input, "-"))
{
originalPop = pop();
sum = push(pop() - originalPop);
}
// Multiplication
else if (stringEqualTo(input, "*"))
{
sum = push(pop() * pop());
}
// Division
else if (stringEqualTo(input, "/"))
{
originalPop = pop();
sum = push(originalPop / pop());
}
}
else
{
// push the value 'numIn' onto the stack.
push(numIn);
}
}
}while(status != EOF);
// Print results
printf("%ld\n", sum);
return 0;
}