This works when I input the values using the keyboard, but I want to have the array declared and the whole string passed on from main() to getop() and still have the same result. I feel the getchar() in the getop() is the problem. Any suggestions how I can do this?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 50
#define MAXOP 100 /* max size of operand or operator */
#define NUMBER '0' /* signal that a number was found */
#define MAXVAL 100 /* maximum depth of val stack */
int getop(char []);
void push(double);
double pop(void);
main()
{
int type;
double op2;
double a, b,q;
char array[MAXOP];
char array[]= "2 4 +";
while ((type = getop(array)) != EOF) {
switch (type) {
case NUMBER: push(atof(array));
break;
case '+': push(pop() + pop());
break;
case '*': push(pop() * pop());
break;
case '-': op2 = pop();
push(pop() - op2);
break;
case '/': op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
case '\n': printf("\t%.8g\n", pop());
getchar();
break;
default: printf("error: unknown command %s\n", array);
break;
}
}
return 0;
}
int sp=0;
double val[MAXVAL];
void push(double f)
{
if (sp < MAXVAL)
val[sp++] = f;
else
printf("error: stack full, can’t push %g\n", f);
}
double pop(void)
{
if (sp > 0)
return val[--sp];
else {
printf("error: stack empty\n");
return 0.0;
}
}
int getop(char s[]){
int i,c;
while ((s[0]=c=getchar()) == ' ' || c == '\t');
s[1] = '\0';
if (!isdigit (c) && c != '.')
return c;
i = 0;
if (isdigit(c))
while (isdigit(s[++i]=c=getchar()));
if ( c == '.')
while (isdigit(s[++i]=c=getchar()));
s[i] = '\0';
if ( c != EOF)
ungetch(c);
return NUMBER;
}